Add explicit types to NB kernel type enums
[alexxy/gromacs.git] / src / gromacs / gpu_utils / devicebuffer_sycl.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2020, 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_SYCL_H
36 #define GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H
37
38 /*! \libinternal \file
39  *  \brief Implements the DeviceBuffer type and routines for SYCL.
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 Artem Zhmurov <zhmurov@gmail.com>
44  *  \author Erik Lindahl <erik.lindahl@gmail.com>
45  *  \author Andrey Alekseenko <al42and@gmail.com>
46  *
47  *  \inlibraryapi
48  */
49
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/gmxsycl.h"
54 #include "gromacs/gpu_utils/gpu_utils.h" //only for GpuApiCallBehavior
55 #include "gromacs/gpu_utils/gputraits_sycl.h"
56 #include "gromacs/utility/gmxassert.h"
57 #include "gromacs/utility/stringutil.h"
58
59 #ifndef DOXYGEN
60 template<typename T>
61 class DeviceBuffer<T>::ClSyclBufferWrapper : public cl::sycl::buffer<T, 1>
62 {
63     using cl::sycl::buffer<T, 1>::buffer; // Get all the constructors
64 };
65
66 template<typename T>
67 using ClSyclBufferWrapper = typename DeviceBuffer<T>::ClSyclBufferWrapper;
68
69 //! Constructor.
70 template<typename T>
71 DeviceBuffer<T>::DeviceBuffer() : buffer_(nullptr)
72 {
73 }
74
75 //! Destructor.
76 template<typename T>
77 DeviceBuffer<T>::~DeviceBuffer() = default;
78
79 //! Copy constructor (references the same underlying SYCL buffer).
80 template<typename T>
81 DeviceBuffer<T>::DeviceBuffer(DeviceBuffer<T> const& src) :
82     buffer_(new ClSyclBufferWrapper(*src.buffer_))
83 {
84 }
85
86 //! Move constructor.
87 template<typename T>
88 DeviceBuffer<T>::DeviceBuffer(DeviceBuffer<T>&& src) noexcept = default;
89
90 //! Copy assignment (references the same underlying SYCL buffer).
91 template<typename T>
92 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T> const& src)
93 {
94     buffer_.reset(new ClSyclBufferWrapper(*src.buffer_));
95     return *this;
96 }
97
98 //! Move assignment.
99 template<typename T>
100 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T>&& src) noexcept = default;
101
102 /*! \brief Dummy assignment operator to allow compilation of some cross-platform code.
103  *
104  * A hacky way to make SYCL implementation of DeviceBuffer compatible with details of CUDA and
105  * OpenCL implementations.
106  *
107  * \todo Should be removed after DeviceBuffer refactoring.
108  *
109  * \tparam T Type of buffer content.
110  * \param nullPtr \c std::nullptr. Not possible to assign any other pointers.
111  */
112 template<typename T>
113 DeviceBuffer<T>& DeviceBuffer<T>::operator=(std::nullptr_t nullPtr)
114 {
115     buffer_.reset(nullPtr);
116     return *this;
117 }
118
119 #endif // #ifndef DOXYGEN
120
121 /*! \libinternal \brief
122  * Allocates a device-side buffer.
123  * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
124  *
125  * \tparam        ValueType            Raw value type of the \p buffer.
126  * \param[in,out] buffer               Pointer to the device-side buffer.
127  * \param[in]     numValues            Number of values to accommodate.
128  * \param[in]     deviceContext        The buffer's device context-to-be.
129  */
130 template<typename ValueType>
131 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& deviceContext)
132 {
133     /* SYCL does not require binding buffer to a specific context or device. The ::context_bound
134      * property only enforces the use of only given context, and possibly offers some optimizations */
135     const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
136             deviceContext.context()) };
137     buffer->buffer_.reset(
138             new ClSyclBufferWrapper<ValueType>(cl::sycl::range<1>(numValues), bufferProperties));
139 }
140
141 /*! \brief
142  * Frees a device-side buffer.
143  * This does not reset separately stored size/capacity integers,
144  * as this is planned to be a destructor of DeviceBuffer as a proper class,
145  * and no calls on \p buffer should be made afterwards.
146  *
147  * \param[in] buffer  Pointer to the buffer to free.
148  */
149 template<typename ValueType>
150 void freeDeviceBuffer(DeviceBuffer<ValueType>* buffer)
151 {
152     buffer->buffer_.reset(nullptr);
153 }
154
155 /*! \brief
156  * Performs the host-to-device data copy, synchronous or asynchronously on request.
157  *
158  * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
159  * submitted operations are complete, only the ones that are required for \p buffer consistency.
160  *
161  * \tparam        ValueType            Raw value type of the \p buffer.
162  * \param[in,out] buffer               Pointer to the device-side buffer.
163  * \param[in]     hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType.
164  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy into.
165  * \param[in]     numValues            Number of values to copy.
166  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
167  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
168  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
169  *                                     Ignored in SYCL.
170  */
171 template<typename ValueType>
172 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
173                         const ValueType*         hostBuffer,
174                         size_t                   startingOffset,
175                         size_t                   numValues,
176                         const DeviceStream&      deviceStream,
177                         GpuApiCallBehavior       transferKind,
178                         CommandEvent* gmx_unused timingEvent)
179 {
180     if (numValues == 0)
181     {
182         return; // such calls are actually made with empty domains
183     }
184     GMX_ASSERT(buffer, "needs a buffer pointer");
185     GMX_ASSERT(buffer->buffer_, "needs an initialized buffer pointer");
186     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
187
188     cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
189
190     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
191         /* Here and elsewhere in this file, accessor constructor is user instead of a more common
192          * buffer::get_access, since the compiler (icpx 2021.1-beta09) occasionally gets confused
193          * by all the overloads */
194         auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::discard_write>{
195             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
196         };
197         cgh.copy(hostBuffer, d_bufferAccessor);
198     });
199     if (transferKind == GpuApiCallBehavior::Sync)
200     {
201         ev.wait_and_throw();
202     }
203 }
204
205 /*! \brief
206  * Performs the device-to-host data copy, synchronous or asynchronously on request.
207  *
208  * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
209  * submitted operations are complete, only the ones that are required for \p buffer consistency.
210  *
211  * \tparam        ValueType            Raw value type of the \p buffer.
212  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
213  * \param[in]     buffer               Pointer to the device-side buffer.
214  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
215  * \param[in]     numValues            Number of values to copy.
216  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
217  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
218  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
219  *                                     Ignored in SYCL.
220  */
221 template<typename ValueType>
222 void copyFromDeviceBuffer(ValueType*               hostBuffer,
223                           DeviceBuffer<ValueType>* buffer,
224                           size_t                   startingOffset,
225                           size_t                   numValues,
226                           const DeviceStream&      deviceStream,
227                           GpuApiCallBehavior       transferKind,
228                           CommandEvent* gmx_unused timingEvent)
229 {
230     if (numValues == 0)
231     {
232         return; // such calls are actually made with empty domains
233     }
234     GMX_ASSERT(buffer, "needs a buffer pointer");
235     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
236
237     cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
238
239     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
240         const auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::read>{
241             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
242         };
243         cgh.copy(d_bufferAccessor, hostBuffer);
244     });
245     if (transferKind == GpuApiCallBehavior::Sync)
246     {
247         ev.wait_and_throw();
248     }
249 }
250
251 /*! \brief
252  * Clears the device buffer asynchronously.
253  *
254  * \tparam        ValueType       Raw value type of the \p buffer.
255  * \param[in,out] buffer          Pointer to the device-side buffer.
256  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
257  * \param[in]     numValues       Number of values to clear.
258  * \param[in]     deviceStream    GPU stream.
259  */
260 template<typename ValueType>
261 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
262                             size_t                   startingOffset,
263                             size_t                   numValues,
264                             const DeviceStream&      deviceStream)
265 {
266     if (numValues == 0)
267     {
268         return;
269     }
270     GMX_ASSERT(buffer, "needs a buffer pointer");
271
272     const ValueType              pattern{};
273     cl::sycl::buffer<ValueType>& syclBuffer = *(buffer->buffer_);
274
275     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
276         auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::discard_write>{
277             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
278         };
279         cgh.fill(d_bufferAccessor, pattern);
280     });
281 }
282
283 /*! \brief Check the validity of the device buffer.
284  *
285  * Checks if the buffer is valid and if its allocation is big enough.
286  *
287  * \param[in] buffer        Device buffer to be checked.
288  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
289  *
290  * \returns Whether the device buffer exists and has enough capacity.
291  */
292 template<typename T>
293 static gmx_unused bool checkDeviceBuffer(DeviceBuffer<T> buffer, int requiredSize)
294 {
295     return buffer.buffer_ && (static_cast<int>(buffer.buffer_->get_count()) >= requiredSize);
296 }
297
298 /*! \brief Create a texture object for an array of type ValueType.
299  *
300  * Creates the device buffer and copies read-only data for an array of type ValueType.
301  * Like OpenCL, does not really do anything with textures, simply creates a buffer
302  * and initializes it.
303  *
304  * \tparam      ValueType      Raw data type.
305  *
306  * \param[out]  deviceBuffer   Device buffer to store data in.
307  * \param[in]   hostBuffer     Host buffer to get date from.
308  * \param[in]   numValues      Number of elements in the buffer.
309  * \param[in]   deviceContext  GPU device context.
310  */
311 template<typename ValueType>
312 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
313                           DeviceTexture* /* deviceTexture */,
314                           const ValueType*     hostBuffer,
315                           int                  numValues,
316                           const DeviceContext& deviceContext)
317 {
318     GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
319     GMX_ASSERT(deviceBuffer, "Device buffer should be specified.");
320
321     /* Constructing buffer with cl::sycl::buffer(T* data, size_t size) will take ownership
322      * of this memory region making it unusable, which might lead to side-effects.
323      * On the other hand, cl::sycl::buffer(InputIterator<T> begin, InputIterator<T> end) will
324      * initialize the buffer without affecting ownership of the memory, although
325      * it will consume extra memory on host. */
326     const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
327             deviceContext.context()) };
328     deviceBuffer->buffer_.reset(new ClSyclBufferWrapper<ValueType>(
329             hostBuffer, hostBuffer + numValues, bufferProperties));
330 }
331
332 /*! \brief Release the OpenCL device buffer.
333  *
334  * \tparam        ValueType     Raw data type.
335  *
336  * \param[in,out] deviceBuffer  Device buffer to store data in.
337  */
338 template<typename ValueType>
339 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& /* deviceTexture */)
340 {
341     deviceBuffer->buffer_.reset(nullptr);
342 }
343
344 #endif // GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H