2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
35 #ifndef GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H
36 #define GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H
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.
43 * \author Artem Zhmurov <zhmurov@gmail.com>
44 * \author Erik Lindahl <erik.lindahl@gmail.com>
45 * \author Andrey Alekseenko <al42and@gmail.com>
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"
64 class DeviceBuffer<T>::ClSyclBufferWrapper : public cl::sycl::buffer<T, 1>
66 using cl::sycl::buffer<T, 1>::buffer; // Get all the constructors
70 using ClSyclBufferWrapper = typename DeviceBuffer<T>::ClSyclBufferWrapper;
74 DeviceBuffer<T>::DeviceBuffer() : buffer_(nullptr)
80 DeviceBuffer<T>::~DeviceBuffer() = default;
82 //! Copy constructor (references the same underlying SYCL buffer).
84 DeviceBuffer<T>::DeviceBuffer(DeviceBuffer<T> const& src)
88 buffer_ = std::make_unique<ClSyclBufferWrapper>(*src.buffer_);
98 DeviceBuffer<T>::DeviceBuffer(DeviceBuffer<T>&& src) noexcept = default;
100 //! Copy assignment (references the same underlying SYCL buffer).
102 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T> const& src)
106 buffer_ = std::make_unique<ClSyclBufferWrapper>(*src.buffer_);
110 buffer_.reset(nullptr);
117 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T>&& src) noexcept = default;
119 /*! \brief Dummy assignment operator to allow compilation of some cross-platform code.
121 * A hacky way to make SYCL implementation of DeviceBuffer compatible with details of CUDA and
122 * OpenCL implementations.
124 * \todo Should be removed after DeviceBuffer refactoring.
126 * \tparam T Type of buffer content.
127 * \param nullPtr \c std::nullptr. Not possible to assign any other pointers.
130 DeviceBuffer<T>& DeviceBuffer<T>::operator=(std::nullptr_t nullPtr)
132 buffer_.reset(nullPtr);
137 namespace gmx::internal
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
146 * Thin wrapper around placeholder accessor that allows implicit construction from \c DeviceBuffer.
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.
153 * \tparam T Type of buffer content.
154 * \tparam mode Access mode.
156 template<class T, cl::sycl::access::mode mode>
157 class DeviceAccessor : public gmx::internal::PlaceholderAccessor<T, mode>
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))
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)))
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");
181 //! Helper function to get sycl:buffer object from DeviceBuffer wrapper, with a sanity check.
182 static inline cl::sycl::buffer<T, 1>& getSyclBuffer(DeviceBuffer<T>& buffer)
184 GMX_ASSERT(bool(buffer), "Trying to construct accessor from an uninitialized buffer");
185 return *buffer.buffer_;
189 namespace gmx::internal
191 //! A "blackhole" class to be used when we want to ignore an argument to a function.
192 struct EmptyClassThatIgnoresConstructorArguments
194 template<class... Args>
195 [[maybe_unused]] EmptyClassThatIgnoresConstructorArguments(Args&&... /*args*/)
199 } // namespace gmx::internal
202 * Helper class to be used as function argument. Will either correspond to a device accessor, or an empty class.
206 template <bool doFoo>
207 void getBarKernel(handler& cgh, OptionalAccessor<float, mode::read, doFoo> a_fooPrms)
210 cgh.require(a_fooPrms);
211 // Can only use a_fooPrms if doFoo == true
214 template <bool doFoo>
215 void callBar(DeviceBuffer<float> b_fooPrms)
217 // If doFoo is false, b_fooPrms will be ignored (can be not initialized).
218 // Otherwise, an accessor will be built (b_fooPrms must be a valid buffer).
219 auto kernel = getBarKernel<doFoo>(b_fooPrms);
220 // If the accessor in not enabled, anything can be passed as its ctor argument.
221 auto kernel2 = getBarKernel<false>(nullptr_t);
225 * \tparam T Data type of the underlying buffer
226 * \tparam mode Access mode of the accessor
227 * \tparam enabled Compile-time flag indicating whether we want to actually create an accessor.
229 template<class T, cl::sycl::access::mode mode, bool enabled>
230 using OptionalAccessor =
231 std::conditional_t<enabled, DeviceAccessor<T, mode>, gmx::internal::EmptyClassThatIgnoresConstructorArguments>;
233 #endif // #ifndef DOXYGEN
235 /*! \brief Check the validity of the device buffer.
237 * Checks if the buffer is valid and if its allocation is big enough.
239 * \param[in] buffer Device buffer to be checked.
240 * \param[in] requiredSize Number of elements that the buffer will have to accommodate.
242 * \returns Whether the device buffer exists and has enough capacity.
245 static gmx_unused bool checkDeviceBuffer(const DeviceBuffer<T>& buffer, int requiredSize)
247 return buffer.buffer_ && (static_cast<int>(buffer.buffer_->get_count()) >= requiredSize);
250 /*! \libinternal \brief
251 * Allocates a device-side buffer.
252 * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
254 * \tparam ValueType Raw value type of the \p buffer.
255 * \param[in,out] buffer Pointer to the device-side buffer.
256 * \param[in] numValues Number of values to accommodate.
257 * \param[in] deviceContext The buffer's device context-to-be.
259 template<typename ValueType>
260 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& deviceContext)
262 /* SYCL does not require binding buffer to a specific context or device. The ::context_bound
263 * property only enforces the use of only given context, and possibly offers some optimizations */
264 const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
265 deviceContext.context()) };
266 buffer->buffer_.reset(
267 new ClSyclBufferWrapper<ValueType>(cl::sycl::range<1>(numValues), bufferProperties));
271 * Frees a device-side buffer.
272 * This does not reset separately stored size/capacity integers,
273 * as this is planned to be a destructor of DeviceBuffer as a proper class,
274 * and no calls on \p buffer should be made afterwards.
276 * \param[in] buffer Pointer to the buffer to free.
278 template<typename ValueType>
279 void freeDeviceBuffer(DeviceBuffer<ValueType>* buffer)
281 buffer->buffer_.reset(nullptr);
285 * Performs the host-to-device data copy, synchronous or asynchronously on request.
287 * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
288 * submitted operations are complete, only the ones that are required for \p buffer consistency.
290 * \tparam ValueType Raw value type of the \p buffer.
291 * \param[in,out] buffer Pointer to the device-side buffer.
292 * \param[in] hostBuffer Pointer to the raw host-side memory, also typed \p ValueType.
293 * \param[in] startingOffset Offset (in values) at the device-side buffer to copy into.
294 * \param[in] numValues Number of values to copy.
295 * \param[in] deviceStream GPU stream to perform asynchronous copy in.
296 * \param[in] transferKind Copy type: synchronous or asynchronous.
297 * \param[out] timingEvent A pointer to the H2D copy timing event to be filled in.
300 template<typename ValueType>
301 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
302 const ValueType* hostBuffer,
303 size_t startingOffset,
305 const DeviceStream& deviceStream,
306 GpuApiCallBehavior transferKind,
307 CommandEvent* gmx_unused timingEvent)
311 return; // such calls are actually made with empty domains
313 GMX_ASSERT(buffer, "needs a buffer pointer");
314 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
316 GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
317 "buffer too small or not initialized");
319 cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
321 cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
322 /* Here and elsewhere in this file, accessor constructor is user instead of a more common
323 * buffer::get_access, since the compiler (icpx 2021.1-beta09) occasionally gets confused
324 * by all the overloads */
325 auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::discard_write>{
326 syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
328 cgh.copy(hostBuffer, d_bufferAccessor);
330 if (transferKind == GpuApiCallBehavior::Sync)
337 * Performs the device-to-host data copy, synchronous or asynchronously on request.
339 * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
340 * submitted operations are complete, only the ones that are required for \p buffer consistency.
342 * \tparam ValueType Raw value type of the \p buffer.
343 * \param[in,out] hostBuffer Pointer to the raw host-side memory, also typed \p ValueType
344 * \param[in] buffer Pointer to the device-side buffer.
345 * \param[in] startingOffset Offset (in values) at the device-side buffer to copy from.
346 * \param[in] numValues Number of values to copy.
347 * \param[in] deviceStream GPU stream to perform asynchronous copy in.
348 * \param[in] transferKind Copy type: synchronous or asynchronous.
349 * \param[out] timingEvent A pointer to the H2D copy timing event to be filled in.
352 template<typename ValueType>
353 void copyFromDeviceBuffer(ValueType* hostBuffer,
354 DeviceBuffer<ValueType>* buffer,
355 size_t startingOffset,
357 const DeviceStream& deviceStream,
358 GpuApiCallBehavior transferKind,
359 CommandEvent* gmx_unused timingEvent)
363 return; // such calls are actually made with empty domains
365 GMX_ASSERT(buffer, "needs a buffer pointer");
366 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
368 GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
369 "buffer too small or not initialized");
371 cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
373 cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
374 const auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::read>{
375 syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
377 cgh.copy(d_bufferAccessor, hostBuffer);
379 if (transferKind == GpuApiCallBehavior::Sync)
386 * Performs the device-to-device data copy, synchronous or asynchronously on request.
388 * \tparam ValueType Raw value type of the \p buffer.
390 template<typename ValueType>
391 void copyBetweenDeviceBuffers(DeviceBuffer<ValueType>* /* destinationDeviceBuffer */,
392 DeviceBuffer<ValueType>* /* sourceDeviceBuffer */,
393 size_t /* numValues */,
394 const DeviceStream& /* deviceStream */,
395 GpuApiCallBehavior /* transferKind */,
396 CommandEvent* /*timingEvent*/)
399 gmx_fatal(FARGS, "D2D copy stub was called. Not yet implemented in SYCL.");
403 namespace gmx::internal
405 /*! \brief Helper function to clear device buffer.
407 * Not applicable to GROMACS's float3 (a.k.a. gmx::RVec) and other custom types.
408 * From SYCL specs: "T must be a scalar value or a SYCL vector type."
410 template<typename ValueType>
411 cl::sycl::event fillSyclBufferWithNull(cl::sycl::buffer<ValueType, 1>& buffer,
412 size_t startingOffset,
414 cl::sycl::queue queue)
416 using cl::sycl::access::mode;
417 const cl::sycl::range<1> range(numValues);
418 const cl::sycl::id<1> offset(startingOffset);
419 const ValueType pattern = ValueType(0); // SYCL vectors support initialization by scalar
421 return queue.submit([&](cl::sycl::handler& cgh) {
422 auto d_bufferAccessor =
423 cl::sycl::accessor<ValueType, 1, mode::discard_write>{ buffer, cgh, range, offset };
424 cgh.fill(d_bufferAccessor, pattern);
428 //! \brief Helper function to clear device buffer of type float3.
430 inline cl::sycl::event fillSyclBufferWithNull(cl::sycl::buffer<Float3, 1>& buffer,
431 size_t startingOffset,
433 cl::sycl::queue queue)
435 cl::sycl::buffer<float, 1> bufferAsFloat = buffer.reinterpret<float, 1>(buffer.get_count() * DIM);
436 return fillSyclBufferWithNull<float>(
437 bufferAsFloat, startingOffset * DIM, numValues * DIM, std::move(queue));
439 } // namespace gmx::internal
442 * Clears the device buffer asynchronously.
444 * \tparam ValueType Raw value type of the \p buffer.
445 * \param[in,out] buffer Pointer to the device-side buffer.
446 * \param[in] startingOffset Offset (in values) at the device-side buffer to start clearing at.
447 * \param[in] numValues Number of values to clear.
448 * \param[in] deviceStream GPU stream.
450 template<typename ValueType>
451 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
452 size_t startingOffset,
454 const DeviceStream& deviceStream)
460 GMX_ASSERT(buffer, "needs a buffer pointer");
462 GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
463 "buffer too small or not initialized");
465 cl::sycl::buffer<ValueType>& syclBuffer = *(buffer->buffer_);
467 gmx::internal::fillSyclBufferWithNull<ValueType>(
468 syclBuffer, startingOffset, numValues, deviceStream.stream());
471 /*! \brief Create a texture object for an array of type ValueType.
473 * Creates the device buffer and copies read-only data for an array of type ValueType.
474 * Like OpenCL, does not really do anything with textures, simply creates a buffer
475 * and initializes it.
477 * \tparam ValueType Raw data type.
479 * \param[out] deviceBuffer Device buffer to store data in.
480 * \param[in] hostBuffer Host buffer to get date from.
481 * \param[in] numValues Number of elements in the buffer.
482 * \param[in] deviceContext GPU device context.
484 template<typename ValueType>
485 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
486 DeviceTexture* /* deviceTexture */,
487 const ValueType* hostBuffer,
489 const DeviceContext& deviceContext)
491 GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
492 GMX_ASSERT(deviceBuffer, "Device buffer should be specified.");
494 /* Constructing buffer with cl::sycl::buffer(T* data, size_t size) will take ownership
495 * of this memory region making it unusable, which might lead to side-effects.
496 * On the other hand, cl::sycl::buffer(InputIterator<T> begin, InputIterator<T> end) will
497 * initialize the buffer without affecting ownership of the memory, although
498 * it will consume extra memory on host. */
499 const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
500 deviceContext.context()) };
501 deviceBuffer->buffer_.reset(new ClSyclBufferWrapper<ValueType>(
502 hostBuffer, hostBuffer + numValues, bufferProperties));
505 /*! \brief Release the OpenCL device buffer.
507 * \tparam ValueType Raw data type.
509 * \param[in,out] deviceBuffer Device buffer to store data in.
511 template<typename ValueType>
512 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& /* deviceTexture */)
514 deviceBuffer->buffer_.reset(nullptr);
517 #endif // GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H