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