Device management: Add SYCL DeviceBuffer
[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 #endif // #ifndef DOXYGEN
103
104 /*! \libinternal \brief
105  * Allocates a device-side buffer.
106  * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
107  *
108  * \tparam        ValueType            Raw value type of the \p buffer.
109  * \param[in,out] buffer               Pointer to the device-side buffer.
110  * \param[in]     numValues            Number of values to accommodate.
111  * \param[in]     deviceContext        The buffer's device context-to-be.
112  */
113 template<typename ValueType>
114 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& deviceContext)
115 {
116     /* SYCL does not require binding buffer to a specific context or device. The ::context_bound
117      * property only enforces the use of only given context, and possibly offers some optimizations */
118     const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
119             deviceContext.context()) };
120     buffer->buffer_.reset(
121             new ClSyclBufferWrapper<ValueType>(cl::sycl::range<1>(numValues), bufferProperties));
122 }
123
124 /*! \brief
125  * Frees a device-side buffer.
126  * This does not reset separately stored size/capacity integers,
127  * as this is planned to be a destructor of DeviceBuffer as a proper class,
128  * and no calls on \p buffer should be made afterwards.
129  *
130  * \param[in] buffer  Pointer to the buffer to free.
131  */
132 template<typename ValueType>
133 void freeDeviceBuffer(DeviceBuffer<ValueType>* buffer)
134 {
135     buffer->buffer_.reset(nullptr);
136 }
137
138 /*! \brief
139  * Performs the host-to-device data copy, synchronous or asynchronously on request.
140  *
141  * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
142  * submitted operations are complete, only the ones that are required for \p buffer consistency.
143  *
144  * \tparam        ValueType            Raw value type of the \p buffer.
145  * \param[in,out] buffer               Pointer to the device-side buffer.
146  * \param[in]     hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType.
147  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy into.
148  * \param[in]     numValues            Number of values to copy.
149  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
150  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
151  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
152  *                                     Ignored in SYCL.
153  */
154 template<typename ValueType>
155 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
156                         const ValueType*         hostBuffer,
157                         size_t                   startingOffset,
158                         size_t                   numValues,
159                         const DeviceStream&      deviceStream,
160                         GpuApiCallBehavior       transferKind,
161                         CommandEvent* gmx_unused timingEvent)
162 {
163     if (numValues == 0)
164     {
165         return; // such calls are actually made with empty domains
166     }
167     GMX_ASSERT(buffer, "needs a buffer pointer");
168     GMX_ASSERT(buffer->buffer_, "needs an initialized buffer pointer");
169     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
170
171     cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
172
173     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
174         /* Here and elsewhere in this file, accessor constructor is user instead of a more common
175          * buffer::get_access, since the compiler (icpx 2021.1-beta09) occasionally gets confused
176          * by all the overloads */
177         auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::discard_write>{
178             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
179         };
180         cgh.copy(hostBuffer, d_bufferAccessor);
181     });
182     if (transferKind == GpuApiCallBehavior::Sync)
183     {
184         ev.wait_and_throw();
185     }
186 }
187
188 /*! \brief
189  * Performs the device-to-host data copy, synchronous or asynchronously on request.
190  *
191  * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
192  * submitted operations are complete, only the ones that are required for \p buffer consistency.
193  *
194  * \tparam        ValueType            Raw value type of the \p buffer.
195  * \param[in,out] hostBuffer           Pointer to the raw host-side memory, also typed \p ValueType
196  * \param[in]     buffer               Pointer to the device-side buffer.
197  * \param[in]     startingOffset       Offset (in values) at the device-side buffer to copy from.
198  * \param[in]     numValues            Number of values to copy.
199  * \param[in]     deviceStream         GPU stream to perform asynchronous copy in.
200  * \param[in]     transferKind         Copy type: synchronous or asynchronous.
201  * \param[out]    timingEvent          A pointer to the H2D copy timing event to be filled in.
202  *                                     Ignored in SYCL.
203  */
204 template<typename ValueType>
205 void copyFromDeviceBuffer(ValueType*               hostBuffer,
206                           DeviceBuffer<ValueType>* buffer,
207                           size_t                   startingOffset,
208                           size_t                   numValues,
209                           const DeviceStream&      deviceStream,
210                           GpuApiCallBehavior       transferKind,
211                           CommandEvent* gmx_unused timingEvent)
212 {
213     if (numValues == 0)
214     {
215         return; // such calls are actually made with empty domains
216     }
217     GMX_ASSERT(buffer, "needs a buffer pointer");
218     GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
219
220     cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
221
222     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
223         const auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::read>{
224             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
225         };
226         cgh.copy(d_bufferAccessor, hostBuffer);
227     });
228     if (transferKind == GpuApiCallBehavior::Sync)
229     {
230         ev.wait_and_throw();
231     }
232 }
233
234 /*! \brief
235  * Clears the device buffer asynchronously.
236  *
237  * \tparam        ValueType       Raw value type of the \p buffer.
238  * \param[in,out] buffer          Pointer to the device-side buffer.
239  * \param[in]     startingOffset  Offset (in values) at the device-side buffer to start clearing at.
240  * \param[in]     numValues       Number of values to clear.
241  * \param[in]     deviceStream    GPU stream.
242  */
243 template<typename ValueType>
244 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
245                             size_t                   startingOffset,
246                             size_t                   numValues,
247                             const DeviceStream&      deviceStream)
248 {
249     if (numValues == 0)
250     {
251         return;
252     }
253     GMX_ASSERT(buffer, "needs a buffer pointer");
254
255     const ValueType              pattern{};
256     cl::sycl::buffer<ValueType>& syclBuffer = *(buffer->buffer_);
257
258     cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
259         auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::discard_write>{
260             syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
261         };
262         cgh.fill(d_bufferAccessor, pattern);
263     });
264 }
265
266 /*! \brief Check the validity of the device buffer.
267  *
268  * Checks if the buffer is valid and if its allocation is big enough.
269  *
270  * \param[in] buffer        Device buffer to be checked.
271  * \param[in] requiredSize  Number of elements that the buffer will have to accommodate.
272  *
273  * \returns Whether the device buffer exists and has enough capacity.
274  */
275 template<typename T>
276 static gmx_unused bool checkDeviceBuffer(DeviceBuffer<T> buffer, int requiredSize)
277 {
278     return buffer.buffer_ && (static_cast<int>(buffer.buffer_->get_count()) >= requiredSize);
279 }
280
281 /*! \brief Create a texture object for an array of type ValueType.
282  *
283  * Creates the device buffer and copies read-only data for an array of type ValueType.
284  * Like OpenCL, does not really do anything with textures, simply creates a buffer
285  * and initializes it.
286  *
287  * \tparam      ValueType      Raw data type.
288  *
289  * \param[out]  deviceBuffer   Device buffer to store data in.
290  * \param[in]   hostBuffer     Host buffer to get date from.
291  * \param[in]   numValues      Number of elements in the buffer.
292  * \param[in]   deviceContext  GPU device context.
293  */
294 template<typename ValueType>
295 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
296                           DeviceTexture* /* deviceTexture */,
297                           const ValueType*     hostBuffer,
298                           int                  numValues,
299                           const DeviceContext& deviceContext)
300 {
301     GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
302     GMX_ASSERT(deviceBuffer, "Device buffer should be specified.");
303
304     /* Constructing buffer with cl::sycl::buffer(T* data, size_t size) will take ownership
305      * of this memory region making it unusable, which might lead to side-effects.
306      * On the other hand, cl::sycl::buffer(InputIterator<T> begin, InputIterator<T> end) will
307      * initialize the buffer without affecting ownership of the memory, although
308      * it will consume extra memory on host. */
309     const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
310             deviceContext.context()) };
311     deviceBuffer->buffer_.reset(new ClSyclBufferWrapper<ValueType>(
312             hostBuffer, hostBuffer + numValues, bufferProperties));
313 }
314
315 /*! \brief Release the OpenCL device buffer.
316  *
317  * \tparam        ValueType     Raw data type.
318  *
319  * \param[in,out] deviceBuffer  Device buffer to store data in.
320  */
321 template<typename ValueType>
322 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& /* deviceTexture */)
323 {
324     deviceBuffer->buffer_.reset(nullptr);
325 }
326
327 #endif // GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H