Disable fastmath with OpenCL on Intel devices
[alexxy/gromacs.git] / src / gromacs / gpu_utils / devicebuffer.cuh
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2018,2019,2020,2021, 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 #ifndef GMX_GPU_UTILS_DEVICEBUFFER_CUH
36 #define GMX_GPU_UTILS_DEVICEBUFFER_CUH
37
38 /*! \libinternal \file
39  *  \brief Implements the DeviceBuffer type and routines for CUDA.
40  *  Should only be included directly by the main DeviceBuffer file devicebuffer.h.
41  *  TODO: the intent is for DeviceBuffer to become a class.
42  *
43  *  \author Aleksei Iupinov <a.yupinov@gmail.com>
44  *
45  *  \inlibraryapi
46  */
47
48 #include "gromacs/gpu_utils/cuda_arch_utils.cuh"
49 #include "gromacs/gpu_utils/cudautils.cuh"
50 #include "gromacs/gpu_utils/device_context.h"
51 #include "gromacs/gpu_utils/device_stream.h"
52 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
53 #include "gromacs/gpu_utils/gpu_utils.h" //only for GpuApiCallBehavior
54 #include "gromacs/gpu_utils/gputraits.cuh"
55 #include "gromacs/utility/gmxassert.h"
56 #include "gromacs/utility/stringutil.h"
57
58 /*! \brief
59  * Allocates a device-side buffer.
60  * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
61  *
62  * \tparam        ValueType            Raw value type of the \p buffer.
63  * \param[in,out] buffer               Pointer to the device-side buffer.
64  * \param[in]     numValues            Number of values to accommodate.
65  * \param[in]     deviceContext        The buffer's dummy device  context - not managed explicitly in CUDA RT.
66  */
67 template<typename ValueType>
68 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& /* deviceContext */)
69 {
70     GMX_ASSERT(buffer, "needs a buffer pointer");
71     cudaError_t stat = cudaMalloc(buffer, numValues * sizeof(ValueType));
72     GMX_RELEASE_ASSERT(
73             stat == cudaSuccess,
74             ("Allocation of the device buffer failed. " + gmx::getDeviceErrorString(stat)).c_str());
75 }
76
77 /*! \brief
78  * Frees a device-side buffer.
79  * This does not reset separately stored size/capacity integers,
80  * as this is planned to be a destructor of DeviceBuffer as a proper class,
81  * and no calls on \p buffer should be made afterwards.
82  *
83  * \param[in] buffer  Pointer to the buffer to free.
84  */
85 template<typename DeviceBuffer>
86 void freeDeviceBuffer(DeviceBuffer* buffer)
87 {
88     GMX_ASSERT(buffer, "needs a buffer pointer");
89     if (*buffer)
90     {
91         cudaError_t stat = cudaFree(*buffer);
92         GMX_RELEASE_ASSERT(
93                 stat == cudaSuccess,
94                 ("Freeing of the device buffer failed. " + gmx::getDeviceErrorString(stat)).c_str());
95     }
96 }
97
98 /*! \brief
99  * Performs the host-to-device data copy, synchronous or asynchronously on request.
100  *
101  * \tparam        ValueType            Raw value type of the \p buffer.
102  * \param[in,out] buffer               Pointer to the device-side buffer
103  * \param[in]     hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
104  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy into.
105  * \param[in]     numValues            Number of values to copy.
106  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
107  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
108  * \param[out]    timingEvent          A dummy pointer to the H2D copy timing event to be filled in.
109  *                                     Not used in CUDA implementation.
110  */
111 template<typename ValueType>
112 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
113                         const ValueType*         hostBuffer,
114                         size_t                   startingOffset,
115                         size_t                   numValues,
116                         const DeviceStream&      deviceStream,
117                         GpuApiCallBehavior       transferKind,
118                         CommandEvent* /*timingEvent*/)
119 {
120     if (numValues == 0)
121     {
122         return;
123     }
124     GMX_ASSERT(buffer, "needs a buffer pointer");
125     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
126     cudaError_t  stat;
127     const size_t bytes = numValues * sizeof(ValueType);
128
129     switch (transferKind)
130     {
131         case GpuApiCallBehavior::Async:
132             GMX_ASSERT(isHostMemoryPinned(hostBuffer), "Source host buffer was not pinned for CUDA");
133             stat = cudaMemcpyAsync(*reinterpret_cast<ValueType**>(buffer) + startingOffset,
134                                    hostBuffer,
135                                    bytes,
136                                    cudaMemcpyHostToDevice,
137                                    deviceStream.stream());
138             GMX_RELEASE_ASSERT(
139                     stat == cudaSuccess,
140                     ("Asynchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
141             break;
142
143         case GpuApiCallBehavior::Sync:
144             stat = cudaMemcpy(*reinterpret_cast<ValueType**>(buffer) + startingOffset,
145                               hostBuffer,
146                               bytes,
147                               cudaMemcpyHostToDevice);
148             GMX_RELEASE_ASSERT(
149                     stat == cudaSuccess,
150                     ("Synchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
151             break;
152
153         default: throw;
154     }
155 }
156
157 /*! \brief
158  * Performs the device-to-host data copy, synchronous or asynchronously on request.
159  *
160  * \tparam        ValueType            Raw value type of the \p buffer.
161  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
162  * \param[in]     buffer               Pointer to the device-side buffer
163  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
164  * \param[in]     numValues            Number of values to copy.
165  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
166  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
167  * \param[out]    timingEvent          A dummy pointer to the H2D copy timing event to be filled in.
168  *                                     Not used in CUDA implementation.
169  */
170 template<typename ValueType>
171 void copyFromDeviceBuffer(ValueType*               hostBuffer,
172                           DeviceBuffer<ValueType>* buffer,
173                           size_t                   startingOffset,
174                           size_t                   numValues,
175                           const DeviceStream&      deviceStream,
176                           GpuApiCallBehavior       transferKind,
177                           CommandEvent* /*timingEvent*/)
178 {
179     if (numValues == 0)
180     {
181         return;
182     }
183     GMX_ASSERT(buffer, "needs a buffer pointer");
184     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
185
186     cudaError_t  stat;
187     const size_t bytes = numValues * sizeof(ValueType);
188     switch (transferKind)
189     {
190         case GpuApiCallBehavior::Async:
191             GMX_ASSERT(isHostMemoryPinned(hostBuffer),
192                        "Destination host buffer was not pinned for CUDA");
193             stat = cudaMemcpyAsync(hostBuffer,
194                                    *reinterpret_cast<ValueType**>(buffer) + startingOffset,
195                                    bytes,
196                                    cudaMemcpyDeviceToHost,
197                                    deviceStream.stream());
198             GMX_RELEASE_ASSERT(
199                     stat == cudaSuccess,
200                     ("Asynchronous D2H copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
201             break;
202
203         case GpuApiCallBehavior::Sync:
204             stat = cudaMemcpy(hostBuffer,
205                               *reinterpret_cast<ValueType**>(buffer) + startingOffset,
206                               bytes,
207                               cudaMemcpyDeviceToHost);
208             GMX_RELEASE_ASSERT(
209                     stat == cudaSuccess,
210                     ("Synchronous D2H copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
211             break;
212
213         default: throw;
214     }
215 }
216
217 /*! \brief
218  * Performs the device-to-device data copy, synchronous or asynchronously on request.
219  *
220  * \tparam        ValueType                Raw value type of the \p buffer.
221  * \param[in,out] destinationDeviceBuffer  Device-side buffer to copy to
222  * \param[in]     sourceDeviceBuffer       Device-side buffer to copy from
223  * \param[in]     numValues                Number of values to copy.
224  * \param[in]     deviceStream             GPU stream to perform asynchronous copy in.
225  * \param[in]     transferKind             Copy type: synchronous or asynchronous.
226  * \param[out]    timingEvent              A dummy pointer to the D2D copy timing event to be filled
227  * in. Not used in CUDA implementation.
228  */
229 template<typename ValueType>
230 void copyBetweenDeviceBuffers(DeviceBuffer<ValueType>* destinationDeviceBuffer,
231                               DeviceBuffer<ValueType>* sourceDeviceBuffer,
232                               size_t                   numValues,
233                               const DeviceStream&      deviceStream,
234                               GpuApiCallBehavior       transferKind,
235                               CommandEvent* /*timingEvent*/)
236 {
237     if (numValues == 0)
238     {
239         return;
240     }
241     GMX_ASSERT(destinationDeviceBuffer, "needs a destination buffer pointer");
242     GMX_ASSERT(sourceDeviceBuffer, "needs a source buffer pointer");
243
244     cudaError_t  stat;
245     const size_t bytes = numValues * sizeof(ValueType);
246     switch (transferKind)
247     {
248         case GpuApiCallBehavior::Async:
249             stat = cudaMemcpyAsync(*destinationDeviceBuffer,
250                                    *sourceDeviceBuffer,
251                                    bytes,
252                                    cudaMemcpyDeviceToDevice,
253                                    deviceStream.stream());
254             GMX_RELEASE_ASSERT(
255                     stat == cudaSuccess,
256                     ("Asynchronous D2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
257             break;
258
259         case GpuApiCallBehavior::Sync:
260             stat = cudaMemcpy(*destinationDeviceBuffer, *sourceDeviceBuffer, bytes, cudaMemcpyDeviceToDevice);
261             GMX_RELEASE_ASSERT(
262                     stat == cudaSuccess,
263                     ("Synchronous D2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
264             break;
265
266         default: throw;
267     }
268 }
269
270 /*! \brief
271  * Clears the device buffer asynchronously.
272  *
273  * \tparam        ValueType       Raw value type of the \p buffer.
274  * \param[in,out] buffer          Pointer to the device-side buffer
275  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
276  * \param[in]     numValues       Number of values to clear.
277  * \param[in]     deviceStream    GPU stream.
278  */
279 template<typename ValueType>
280 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
281                             size_t                   startingOffset,
282                             size_t                   numValues,
283                             const DeviceStream&      deviceStream)
284 {
285     if (numValues == 0)
286     {
287         return;
288     }
289     GMX_ASSERT(buffer, "needs a buffer pointer");
290     const size_t bytes   = numValues * sizeof(ValueType);
291     const char   pattern = 0;
292
293     cudaError_t stat = cudaMemsetAsync(
294             *reinterpret_cast<ValueType**>(buffer) + startingOffset, pattern, bytes, deviceStream.stream());
295     GMX_RELEASE_ASSERT(stat == cudaSuccess,
296                        ("Couldn't clear the device buffer. " + gmx::getDeviceErrorString(stat)).c_str());
297 }
298
299 /*! \brief Check the validity of the device buffer.
300  *
301  * Checks if the buffer is not nullptr.
302  *
303  * \todo Add checks on the buffer size when it will be possible.
304  *
305  * \param[in] buffer        Device buffer to be checked.
306  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
307  *
308  * \returns Whether the device buffer can be set.
309  */
310 template<typename T>
311 gmx_unused static bool checkDeviceBuffer(DeviceBuffer<T> buffer, gmx_unused int requiredSize)
312 {
313     GMX_ASSERT(buffer != nullptr, "The device pointer is nullptr");
314     return buffer != nullptr;
315 }
316
317 //! Device texture wrapper.
318 using DeviceTexture = cudaTextureObject_t;
319
320 /*! \brief Create a texture object for an array of type ValueType.
321  *
322  * Creates the device buffer, copies data and binds texture object for an array of type ValueType.
323  *
324  * \todo Test if using textures is still relevant on modern hardware.
325  *
326  * \tparam      ValueType      Raw data type.
327  *
328  * \param[out]  deviceBuffer   Device buffer to store data in.
329  * \param[out]  deviceTexture  Device texture object to initialize.
330  * \param[in]   hostBuffer     Host buffer to get date from
331  * \param[in]   numValues      Number of elements in the buffer.
332  * \param[in]   deviceContext  GPU device context.
333  */
334 template<typename ValueType>
335 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
336                           DeviceTexture*           deviceTexture,
337                           const ValueType*         hostBuffer,
338                           int                      numValues,
339                           const DeviceContext&     deviceContext)
340 {
341     if (numValues == 0)
342     {
343         return;
344     }
345     GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
346
347     allocateDeviceBuffer(deviceBuffer, numValues, deviceContext);
348
349     const size_t sizeInBytes = numValues * sizeof(ValueType);
350
351     cudaError_t stat = cudaMemcpy(
352             *reinterpret_cast<ValueType**>(deviceBuffer), hostBuffer, sizeInBytes, cudaMemcpyHostToDevice);
353
354     GMX_RELEASE_ASSERT(stat == cudaSuccess,
355                        ("Synchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str());
356
357     if (!c_disableCudaTextures)
358     {
359         cudaResourceDesc rd;
360         cudaTextureDesc  td;
361
362         memset(&rd, 0, sizeof(rd));
363         rd.resType                = cudaResourceTypeLinear;
364         rd.res.linear.devPtr      = *deviceBuffer;
365         rd.res.linear.desc        = cudaCreateChannelDesc<ValueType>();
366         rd.res.linear.sizeInBytes = sizeInBytes;
367
368         memset(&td, 0, sizeof(td));
369         td.readMode = cudaReadModeElementType;
370         stat        = cudaCreateTextureObject(deviceTexture, &rd, &td, nullptr);
371         GMX_RELEASE_ASSERT(
372                 stat == cudaSuccess,
373                 ("Binding of the texture object failed. " + gmx::getDeviceErrorString(stat)).c_str());
374     }
375 }
376
377 /*! \brief Unbind the texture and release the CUDA texture object.
378  *
379  * \tparam         ValueType      Raw data type
380  *
381  * \param[in,out]  deviceBuffer   Device buffer to store data in.
382  * \param[in,out]  deviceTexture  Device texture object to unbind.
383  */
384 template<typename ValueType>
385 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, const DeviceTexture* deviceTexture)
386 {
387     if (!c_disableCudaTextures && deviceTexture && deviceBuffer)
388     {
389         cudaError_t stat = cudaDestroyTextureObject(*deviceTexture);
390         GMX_RELEASE_ASSERT(
391                 stat == cudaSuccess,
392                 ("Destruction of the texture object failed. " + gmx::getDeviceErrorString(stat)).c_str());
393     }
394     freeDeviceBuffer(deviceBuffer);
395 }
396
397 #endif