187b7cf9311ca00ef03019ed538fb5b92acb1f96
[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,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_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 <utility>
51
52 #include "gromacs/gpu_utils/device_context.h"
53 #include "gromacs/gpu_utils/device_stream.h"
54 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
55 #include "gromacs/gpu_utils/gmxsycl.h"
56 #include "gromacs/gpu_utils/gpu_utils.h" //only for GpuApiCallBehavior
57 #include "gromacs/gpu_utils/gputraits_sycl.h"
58 #include "gromacs/utility/fatalerror.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/stringutil.h"
61
62 #ifndef DOXYGEN
63 template<typename T>
64 class DeviceBuffer<T>::ClSyclBufferWrapper : public cl::sycl::buffer<T, 1>
65 {
66     using cl::sycl::buffer<T, 1>::buffer; // Get all the constructors
67 };
68
69 template<typename T>
70 using ClSyclBufferWrapper = typename DeviceBuffer<T>::ClSyclBufferWrapper;
71
72 //! Constructor.
73 template<typename T>
74 DeviceBuffer<T>::DeviceBuffer() : buffer_(nullptr)
75 {
76 }
77
78 //! Destructor.
79 template<typename T>
80 DeviceBuffer<T>::~DeviceBuffer() = default;
81
82 //! Copy constructor (references the same underlying SYCL buffer).
83 template<typename T>
84 DeviceBuffer<T>::DeviceBuffer(DeviceBuffer<T> const& src) :
85     buffer_(new ClSyclBufferWrapper(*src.buffer_))
86 {
87 }
88
89 //! Move constructor.
90 template<typename T>
91 DeviceBuffer<T>::DeviceBuffer(DeviceBuffer<T>&& src) noexcept = default;
92
93 //! Copy assignment (references the same underlying SYCL buffer).
94 template<typename T>
95 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T> const& src)
96 {
97     buffer_.reset(new ClSyclBufferWrapper(*src.buffer_));
98     return *this;
99 }
100
101 //! Move assignment.
102 template<typename T>
103 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T>&& src) noexcept = default;
104
105 /*! \brief Dummy assignment operator to allow compilation of some cross-platform code.
106  *
107  * A hacky way to make SYCL implementation of DeviceBuffer compatible with details of CUDA and
108  * OpenCL implementations.
109  *
110  * \todo Should be removed after DeviceBuffer refactoring.
111  *
112  * \tparam T Type of buffer content.
113  * \param nullPtr \c std::nullptr. Not possible to assign any other pointers.
114  */
115 template<typename T>
116 DeviceBuffer<T>& DeviceBuffer<T>::operator=(std::nullptr_t nullPtr)
117 {
118     buffer_.reset(nullPtr);
119     return *this;
120 }
121
122
123 namespace gmx::internal
124 {
125 //! Shorthand alias to create a placeholder SYCL accessor with chosen data type and access mode.
126 template<class T, enum cl::sycl::access::mode mode>
127 using PlaceholderAccessor =
128         cl::sycl::accessor<T, 1, mode, cl::sycl::access::target::global_buffer, cl::sycl::access::placeholder::true_t>;
129 } // namespace gmx::internal
130
131 /** \brief
132  * Thin wrapper around placeholder accessor that allows implicit construction from \c DeviceBuffer.
133  *
134  * "Placeholder accessor" is an indicator of the intent to create an accessor for certain buffer
135  * of a certain type, that is not yet bound to a specific command group handler (device). Such
136  * accessors can be created outside SYCL kernels, which is helpful if we want to pass them as
137  * function arguments.
138  *
139  * \tparam T Type of buffer content.
140  * \tparam mode Access mode.
141  */
142 template<class T, enum cl::sycl::access::mode mode>
143 class DeviceAccessor : public gmx::internal::PlaceholderAccessor<T, mode>
144 {
145 public:
146     // Inherit all the constructors
147     using gmx::internal::PlaceholderAccessor<T, mode>::PlaceholderAccessor;
148     //! Construct Accessor from DeviceBuffer (must be initialized)
149     DeviceAccessor(DeviceBuffer<T>& buffer) :
150         gmx::internal::PlaceholderAccessor<T, mode>(getSyclBuffer(buffer))
151     {
152     }
153     //! Construct read-only Accessor from a const DeviceBuffer (must be initialized)
154     DeviceAccessor(const DeviceBuffer<T>& buffer) :
155         gmx::internal::PlaceholderAccessor<T, mode>(getSyclBuffer(const_cast<DeviceBuffer<T>&>(buffer)))
156     {
157         /* There were some discussions about making it possible to create read-only sycl::accessor
158          * from a const sycl::buffer (https://github.com/KhronosGroup/SYCL-Docs/issues/10), but
159          * it did not make it into the SYCL2020 standard. So, we have to use const_cast above */
160         /* Using static_assert to ensure that only mode::read accessors can be created from a
161          * const DeviceBuffer. static_assert provides better error messages than std::enable_if. */
162         static_assert(mode == cl::sycl::access::mode::read,
163                       "Can not create non-read-only accessor from a const DeviceBuffer");
164     }
165
166 private:
167     //! Helper function to get sycl:buffer object from DeviceBuffer wrapper, with a sanity check.
168     static inline cl::sycl::buffer<T, 1>& getSyclBuffer(DeviceBuffer<T>& buffer)
169     {
170         GMX_ASSERT(bool(buffer), "Trying to construct accessor from an uninitialized buffer");
171         return *buffer.buffer_;
172     }
173 };
174
175 namespace gmx::internal
176 {
177 //! A "blackhole" class to be used when we want to ignore an argument to a function.
178 struct EmptyClassThatIgnoresConstructorArguments
179 {
180     template<class... Args>
181     [[maybe_unused]] EmptyClassThatIgnoresConstructorArguments(Args&&... /*args*/)
182     {
183     }
184 };
185 } // namespace gmx::internal
186
187 /** \brief
188  * Helper class to be used as function argument. Will either correspond to a device accessor, or an empty class.
189  *
190  * Example usage:
191  * \code
192     template <bool doFoo>
193     void getBarKernel(handler& cgh, OptionalAccessor<float, mode::read, doFoo> a_fooPrms)
194     {
195         if constexpr (doFoo)
196             cgh.require(a_fooPrms);
197         // Can only use a_fooPrms if doFoo == true
198     }
199
200     template <bool doFoo>
201     void callBar(DeviceBuffer<float> b_fooPrms)
202     {
203         // If doFoo is false, b_fooPrms will be ignored (can be not initialized).
204         // Otherwise, an accessor will be built (b_fooPrms must be a valid buffer).
205         auto kernel = getBarKernel<doFoo>(b_fooPrms);
206         // If the accessor in not enabled, anything can be passed as its ctor argument.
207         auto kernel2 = getBarKernel<false>(nullptr_t);
208     }
209  * \endcode
210  *
211  * \tparam T Data type of the underlying buffer
212  * \tparam mode Access mode of the accessor
213  * \tparam enabled Compile-time flag indicating whether we want to actually create an accessor.
214  */
215 template<class T, enum cl::sycl::access::mode mode, bool enabled>
216 using OptionalAccessor =
217         std::conditional_t<enabled, DeviceAccessor<T, mode>, gmx::internal::EmptyClassThatIgnoresConstructorArguments>;
218
219 #endif // #ifndef DOXYGEN
220
221 /*! \brief Check the validity of the device buffer.
222  *
223  * Checks if the buffer is valid and if its allocation is big enough.
224  *
225  * \param[in] buffer        Device buffer to be checked.
226  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
227  *
228  * \returns Whether the device buffer exists and has enough capacity.
229  */
230 template<typename T>
231 static gmx_unused bool checkDeviceBuffer(const DeviceBuffer<T>& buffer, int requiredSize)
232 {
233     return buffer.buffer_ && (static_cast<int>(buffer.buffer_->get_count()) >= requiredSize);
234 }
235
236 /*! \libinternal \brief
237  * Allocates a device-side buffer.
238  * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
239  *
240  * \tparam        ValueType            Raw value type of the \p buffer.
241  * \param[in,out] buffer               Pointer to the device-side buffer.
242  * \param[in]     numValues            Number of values to accommodate.
243  * \param[in]     deviceContext        The buffer's device context-to-be.
244  */
245 template<typename ValueType>
246 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& deviceContext)
247 {
248     /* SYCL does not require binding buffer to a specific context or device. The ::context_bound
249      * property only enforces the use of only given context, and possibly offers some optimizations */
250     const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
251             deviceContext.context()) };
252     buffer->buffer_.reset(
253             new ClSyclBufferWrapper<ValueType>(cl::sycl::range<1>(numValues), bufferProperties));
254 }
255
256 /*! \brief
257  * Frees a device-side buffer.
258  * This does not reset separately stored size/capacity integers,
259  * as this is planned to be a destructor of DeviceBuffer as a proper class,
260  * and no calls on \p buffer should be made afterwards.
261  *
262  * \param[in] buffer  Pointer to the buffer to free.
263  */
264 template<typename ValueType>
265 void freeDeviceBuffer(DeviceBuffer<ValueType>* buffer)
266 {
267     buffer->buffer_.reset(nullptr);
268 }
269
270 /*! \brief
271  * Performs the host-to-device data copy, synchronous or asynchronously on request.
272  *
273  * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
274  * submitted operations are complete, only the ones that are required for \p buffer consistency.
275  *
276  * \tparam        ValueType            Raw value type of the \p buffer.
277  * \param[in,out] buffer               Pointer to the device-side buffer.
278  * \param[in]     hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType.
279  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy into.
280  * \param[in]     numValues            Number of values to copy.
281  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
282  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
283  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
284  *                                     Ignored in SYCL.
285  */
286 template<typename ValueType>
287 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
288                         const ValueType*         hostBuffer,
289                         size_t                   startingOffset,
290                         size_t                   numValues,
291                         const DeviceStream&      deviceStream,
292                         GpuApiCallBehavior       transferKind,
293                         CommandEvent* gmx_unused timingEvent)
294 {
295     if (numValues == 0)
296     {
297         return; // such calls are actually made with empty domains
298     }
299     GMX_ASSERT(buffer, "needs a buffer pointer");
300     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
301
302     GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
303                "buffer too small or not initialized");
304
305     cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
306
307     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
308         /* Here and elsewhere in this file, accessor constructor is user instead of a more common
309          * buffer::get_access, since the compiler (icpx 2021.1-beta09) occasionally gets confused
310          * by all the overloads */
311         auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::discard_write>{
312             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
313         };
314         cgh.copy(hostBuffer, d_bufferAccessor);
315     });
316     if (transferKind == GpuApiCallBehavior::Sync)
317     {
318         ev.wait_and_throw();
319     }
320 }
321
322 /*! \brief
323  * Performs the device-to-host data copy, synchronous or asynchronously on request.
324  *
325  * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
326  * submitted operations are complete, only the ones that are required for \p buffer consistency.
327  *
328  * \tparam        ValueType            Raw value type of the \p buffer.
329  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
330  * \param[in]     buffer               Pointer to the device-side buffer.
331  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
332  * \param[in]     numValues            Number of values to copy.
333  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
334  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
335  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
336  *                                     Ignored in SYCL.
337  */
338 template<typename ValueType>
339 void copyFromDeviceBuffer(ValueType*               hostBuffer,
340                           DeviceBuffer<ValueType>* buffer,
341                           size_t                   startingOffset,
342                           size_t                   numValues,
343                           const DeviceStream&      deviceStream,
344                           GpuApiCallBehavior       transferKind,
345                           CommandEvent* gmx_unused timingEvent)
346 {
347     if (numValues == 0)
348     {
349         return; // such calls are actually made with empty domains
350     }
351     GMX_ASSERT(buffer, "needs a buffer pointer");
352     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
353
354     GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
355                "buffer too small or not initialized");
356
357     cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
358
359     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
360         const auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::read>{
361             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
362         };
363         cgh.copy(d_bufferAccessor, hostBuffer);
364     });
365     if (transferKind == GpuApiCallBehavior::Sync)
366     {
367         ev.wait_and_throw();
368     }
369 }
370
371 /*! \brief
372  * Performs the device-to-device data copy, synchronous or asynchronously on request.
373  *
374  * \tparam        ValueType                Raw value type of the \p buffer.
375  */
376 template<typename ValueType>
377 void copyBetweenDeviceBuffers(DeviceBuffer<ValueType>* /* destinationDeviceBuffer */,
378                               DeviceBuffer<ValueType>* /* sourceDeviceBuffer */,
379                               size_t /* numValues */,
380                               const DeviceStream& /* deviceStream */,
381                               GpuApiCallBehavior /* transferKind */,
382                               CommandEvent* /*timingEvent*/)
383 {
384     // SYCL-TODO
385     gmx_fatal(FARGS, "D2D copy stub was called. Not yet implemented in SYCL.");
386 }
387
388
389 namespace gmx::internal
390 {
391 /*! \brief Helper function to clear device buffer.
392  *
393  * Not applicable to GROMACS's float3 (a.k.a. gmx::RVec) and other custom types.
394  * From SYCL specs: "T must be a scalar value or a SYCL vector type."
395  */
396 template<typename ValueType>
397 cl::sycl::event fillSyclBufferWithNull(cl::sycl::buffer<ValueType, 1>& buffer,
398                                        size_t                          startingOffset,
399                                        size_t                          numValues,
400                                        cl::sycl::queue                 queue)
401 {
402     using cl::sycl::access::mode;
403     const cl::sycl::range<1> range(numValues);
404     const cl::sycl::id<1>    offset(startingOffset);
405     const ValueType pattern = ValueType(0); // SYCL vectors support initialization by scalar
406
407     return queue.submit([&](cl::sycl::handler& cgh) {
408         auto d_bufferAccessor =
409                 cl::sycl::accessor<ValueType, 1, mode::discard_write>{ buffer, cgh, range, offset };
410         cgh.fill(d_bufferAccessor, pattern);
411     });
412 }
413
414 //! \brief Helper function to clear device buffer of type float3.
415 template<>
416 inline cl::sycl::event fillSyclBufferWithNull(cl::sycl::buffer<Float3, 1>& buffer,
417                                               size_t                       startingOffset,
418                                               size_t                       numValues,
419                                               cl::sycl::queue              queue)
420 {
421     cl::sycl::buffer<float, 1> bufferAsFloat = buffer.reinterpret<float, 1>(buffer.get_count() * DIM);
422     return fillSyclBufferWithNull<float>(
423             bufferAsFloat, startingOffset * DIM, numValues * DIM, std::move(queue));
424 }
425 } // namespace gmx::internal
426
427 /*! \brief
428  * Clears the device buffer asynchronously.
429  *
430  * \tparam        ValueType       Raw value type of the \p buffer.
431  * \param[in,out] buffer          Pointer to the device-side buffer.
432  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
433  * \param[in]     numValues       Number of values to clear.
434  * \param[in]     deviceStream    GPU stream.
435  */
436 template<typename ValueType>
437 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
438                             size_t                   startingOffset,
439                             size_t                   numValues,
440                             const DeviceStream&      deviceStream)
441 {
442     if (numValues == 0)
443     {
444         return;
445     }
446     GMX_ASSERT(buffer, "needs a buffer pointer");
447
448     GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
449                "buffer too small or not initialized");
450
451     cl::sycl::buffer<ValueType>& syclBuffer = *(buffer->buffer_);
452
453     gmx::internal::fillSyclBufferWithNull<ValueType>(
454             syclBuffer, startingOffset, numValues, deviceStream.stream());
455 }
456
457 /*! \brief Create a texture object for an array of type ValueType.
458  *
459  * Creates the device buffer and copies read-only data for an array of type ValueType.
460  * Like OpenCL, does not really do anything with textures, simply creates a buffer
461  * and initializes it.
462  *
463  * \tparam      ValueType      Raw data type.
464  *
465  * \param[out]  deviceBuffer   Device buffer to store data in.
466  * \param[in]   hostBuffer     Host buffer to get date from.
467  * \param[in]   numValues      Number of elements in the buffer.
468  * \param[in]   deviceContext  GPU device context.
469  */
470 template<typename ValueType>
471 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
472                           DeviceTexture* /* deviceTexture */,
473                           const ValueType*     hostBuffer,
474                           int                  numValues,
475                           const DeviceContext& deviceContext)
476 {
477     GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
478     GMX_ASSERT(deviceBuffer, "Device buffer should be specified.");
479
480     /* Constructing buffer with cl::sycl::buffer(T* data, size_t size) will take ownership
481      * of this memory region making it unusable, which might lead to side-effects.
482      * On the other hand, cl::sycl::buffer(InputIterator<T> begin, InputIterator<T> end) will
483      * initialize the buffer without affecting ownership of the memory, although
484      * it will consume extra memory on host. */
485     const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
486             deviceContext.context()) };
487     deviceBuffer->buffer_.reset(new ClSyclBufferWrapper<ValueType>(
488             hostBuffer, hostBuffer + numValues, bufferProperties));
489 }
490
491 /*! \brief Release the OpenCL device buffer.
492  *
493  * \tparam        ValueType     Raw data type.
494  *
495  * \param[in,out] deviceBuffer  Device buffer to store data in.
496  */
497 template<typename ValueType>
498 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& /* deviceTexture */)
499 {
500     deviceBuffer->buffer_.reset(nullptr);
501 }
502
503 #endif // GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H