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) :
85 buffer_(new ClSyclBufferWrapper(*src.buffer_))
91 DeviceBuffer<T>::DeviceBuffer(DeviceBuffer<T>&& src) noexcept = default;
93 //! Copy assignment (references the same underlying SYCL buffer).
95 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T> const& src)
97 buffer_.reset(new ClSyclBufferWrapper(*src.buffer_));
103 DeviceBuffer<T>& DeviceBuffer<T>::operator=(DeviceBuffer<T>&& src) noexcept = default;
105 /*! \brief Dummy assignment operator to allow compilation of some cross-platform code.
107 * A hacky way to make SYCL implementation of DeviceBuffer compatible with details of CUDA and
108 * OpenCL implementations.
110 * \todo Should be removed after DeviceBuffer refactoring.
112 * \tparam T Type of buffer content.
113 * \param nullPtr \c std::nullptr. Not possible to assign any other pointers.
116 DeviceBuffer<T>& DeviceBuffer<T>::operator=(std::nullptr_t nullPtr)
118 buffer_.reset(nullPtr);
123 namespace gmx::internal
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
132 * Thin wrapper around placeholder accessor that allows implicit construction from \c DeviceBuffer.
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.
139 * \tparam T Type of buffer content.
140 * \tparam mode Access mode.
142 template<class T, enum cl::sycl::access::mode mode>
143 class DeviceAccessor : public gmx::internal::PlaceholderAccessor<T, mode>
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))
155 //! Helper function to get sycl:buffer object from DeviceBuffer wrapper, with a sanity check.
156 static inline cl::sycl::buffer<T, 1>& getSyclBuffer(DeviceBuffer<T>& buffer)
158 GMX_ASSERT(bool(buffer), "Trying to construct accessor from an uninitialized buffer");
159 return *buffer.buffer_;
163 namespace gmx::internal
165 //! A "blackhole" class to be used when we want to ignore an argument to a function.
166 struct EmptyClassThatIgnoresConstructorArguments
168 template<class... Args>
169 [[maybe_unused]] EmptyClassThatIgnoresConstructorArguments(Args&&... /*args*/)
173 } // namespace gmx::internal
176 * Helper class to be used as function argument. Will either correspond to a device accessor, or an empty class.
180 template <bool doFoo>
181 void getBarKernel(handler& cgh, OptionalAccessor<float, mode::read, doFoo> a_fooPrms)
184 cgh.require(a_fooPrms);
185 // Can only use a_fooPrms if doFoo == true
188 template <bool doFoo>
189 void callBar(DeviceBuffer<float> b_fooPrms)
191 // If doFoo is false, b_fooPrms will be ignored (can be not initialized).
192 // Otherwise, an accessor will be built (b_fooPrms must be a valid buffer).
193 auto kernel = getBarKernel<doFoo>(b_fooPrms);
194 // If the accessor in not enabled, anything can be passed as its ctor argument.
195 auto kernel2 = getBarKernel<false>(nullptr_t);
199 * \tparam T Data type of the underlying buffer
200 * \tparam mode Access mode of the accessor
201 * \tparam enabled Compile-time flag indicating whether we want to actually create an accessor.
203 template<class T, enum cl::sycl::access::mode mode, bool enabled>
204 using OptionalAccessor =
205 std::conditional_t<enabled, DeviceAccessor<T, mode>, gmx::internal::EmptyClassThatIgnoresConstructorArguments>;
207 #endif // #ifndef DOXYGEN
209 /*! \brief Check the validity of the device buffer.
211 * Checks if the buffer is valid and if its allocation is big enough.
213 * \param[in] buffer Device buffer to be checked.
214 * \param[in] requiredSize Number of elements that the buffer will have to accommodate.
216 * \returns Whether the device buffer exists and has enough capacity.
219 static gmx_unused bool checkDeviceBuffer(const DeviceBuffer<T>& buffer, int requiredSize)
221 return buffer.buffer_ && (static_cast<int>(buffer.buffer_->get_count()) >= requiredSize);
224 /*! \libinternal \brief
225 * Allocates a device-side buffer.
226 * It is currently a caller's responsibility to call it only on not-yet allocated buffers.
228 * \tparam ValueType Raw value type of the \p buffer.
229 * \param[in,out] buffer Pointer to the device-side buffer.
230 * \param[in] numValues Number of values to accommodate.
231 * \param[in] deviceContext The buffer's device context-to-be.
233 template<typename ValueType>
234 void allocateDeviceBuffer(DeviceBuffer<ValueType>* buffer, size_t numValues, const DeviceContext& deviceContext)
236 /* SYCL does not require binding buffer to a specific context or device. The ::context_bound
237 * property only enforces the use of only given context, and possibly offers some optimizations */
238 const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
239 deviceContext.context()) };
240 buffer->buffer_.reset(
241 new ClSyclBufferWrapper<ValueType>(cl::sycl::range<1>(numValues), bufferProperties));
245 * Frees a device-side buffer.
246 * This does not reset separately stored size/capacity integers,
247 * as this is planned to be a destructor of DeviceBuffer as a proper class,
248 * and no calls on \p buffer should be made afterwards.
250 * \param[in] buffer Pointer to the buffer to free.
252 template<typename ValueType>
253 void freeDeviceBuffer(DeviceBuffer<ValueType>* buffer)
255 buffer->buffer_.reset(nullptr);
259 * Performs the host-to-device data copy, synchronous or asynchronously on request.
261 * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
262 * submitted operations are complete, only the ones that are required for \p buffer consistency.
264 * \tparam ValueType Raw value type of the \p buffer.
265 * \param[in,out] buffer Pointer to the device-side buffer.
266 * \param[in] hostBuffer Pointer to the raw host-side memory, also typed \p ValueType.
267 * \param[in] startingOffset Offset (in values) at the device-side buffer to copy into.
268 * \param[in] numValues Number of values to copy.
269 * \param[in] deviceStream GPU stream to perform asynchronous copy in.
270 * \param[in] transferKind Copy type: synchronous or asynchronous.
271 * \param[out] timingEvent A pointer to the H2D copy timing event to be filled in.
274 template<typename ValueType>
275 void copyToDeviceBuffer(DeviceBuffer<ValueType>* buffer,
276 const ValueType* hostBuffer,
277 size_t startingOffset,
279 const DeviceStream& deviceStream,
280 GpuApiCallBehavior transferKind,
281 CommandEvent* gmx_unused timingEvent)
285 return; // such calls are actually made with empty domains
287 GMX_ASSERT(buffer, "needs a buffer pointer");
288 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
290 GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
291 "buffer too small or not initialized");
293 cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
295 cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
296 /* Here and elsewhere in this file, accessor constructor is user instead of a more common
297 * buffer::get_access, since the compiler (icpx 2021.1-beta09) occasionally gets confused
298 * by all the overloads */
299 auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::discard_write>{
300 syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
302 cgh.copy(hostBuffer, d_bufferAccessor);
304 if (transferKind == GpuApiCallBehavior::Sync)
311 * Performs the device-to-host data copy, synchronous or asynchronously on request.
313 * Unlike in CUDA and OpenCL, synchronous call does not guarantee that all previously
314 * submitted operations are complete, only the ones that are required for \p buffer consistency.
316 * \tparam ValueType Raw value type of the \p buffer.
317 * \param[in,out] hostBuffer Pointer to the raw host-side memory, also typed \p ValueType
318 * \param[in] buffer Pointer to the device-side buffer.
319 * \param[in] startingOffset Offset (in values) at the device-side buffer to copy from.
320 * \param[in] numValues Number of values to copy.
321 * \param[in] deviceStream GPU stream to perform asynchronous copy in.
322 * \param[in] transferKind Copy type: synchronous or asynchronous.
323 * \param[out] timingEvent A pointer to the H2D copy timing event to be filled in.
326 template<typename ValueType>
327 void copyFromDeviceBuffer(ValueType* hostBuffer,
328 DeviceBuffer<ValueType>* buffer,
329 size_t startingOffset,
331 const DeviceStream& deviceStream,
332 GpuApiCallBehavior transferKind,
333 CommandEvent* gmx_unused timingEvent)
337 return; // such calls are actually made with empty domains
339 GMX_ASSERT(buffer, "needs a buffer pointer");
340 GMX_ASSERT(hostBuffer, "needs a host buffer pointer");
342 GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
343 "buffer too small or not initialized");
345 cl::sycl::buffer<ValueType>& syclBuffer = *buffer->buffer_;
347 cl::sycl::event ev = deviceStream.stream().submit([&](cl::sycl::handler& cgh) {
348 const auto d_bufferAccessor = cl::sycl::accessor<ValueType, 1, cl::sycl::access::mode::read>{
349 syclBuffer, cgh, cl::sycl::range(numValues), cl::sycl::id(startingOffset)
351 cgh.copy(d_bufferAccessor, hostBuffer);
353 if (transferKind == GpuApiCallBehavior::Sync)
360 * Performs the device-to-device data copy, synchronous or asynchronously on request.
362 * \tparam ValueType Raw value type of the \p buffer.
364 template<typename ValueType>
365 void copyBetweenDeviceBuffers(DeviceBuffer<ValueType>* /* destinationDeviceBuffer */,
366 DeviceBuffer<ValueType>* /* sourceDeviceBuffer */,
367 size_t /* numValues */,
368 const DeviceStream& /* deviceStream */,
369 GpuApiCallBehavior /* transferKind */,
370 CommandEvent* /*timingEvent*/)
373 gmx_fatal(FARGS, "D2D copy stub was called. Not yet implemented in SYCL.");
377 namespace gmx::internal
379 /*! \brief Helper function to clear device buffer.
381 * Not applicable to GROMACS's float3 (a.k.a. gmx::RVec) and other custom types.
382 * From SYCL specs: "T must be a scalar value or a SYCL vector type."
384 template<typename ValueType>
385 cl::sycl::event fillSyclBufferWithNull(cl::sycl::buffer<ValueType, 1>& buffer,
386 size_t startingOffset,
388 cl::sycl::queue queue)
390 using cl::sycl::access::mode;
391 const cl::sycl::range<1> range(numValues);
392 const cl::sycl::id<1> offset(startingOffset);
393 const ValueType pattern = ValueType(0); // SYCL vectors support initialization by scalar
395 return queue.submit([&](cl::sycl::handler& cgh) {
396 auto d_bufferAccessor =
397 cl::sycl::accessor<ValueType, 1, mode::discard_write>{ buffer, cgh, range, offset };
398 cgh.fill(d_bufferAccessor, pattern);
402 //! \brief Helper function to clear device buffer of type float3.
404 inline cl::sycl::event fillSyclBufferWithNull(cl::sycl::buffer<Float3, 1>& buffer,
405 size_t startingOffset,
407 cl::sycl::queue queue)
409 cl::sycl::buffer<float, 1> bufferAsFloat = buffer.reinterpret<float, 1>(buffer.get_count() * DIM);
410 return fillSyclBufferWithNull<float>(
411 bufferAsFloat, startingOffset * DIM, numValues * DIM, std::move(queue));
413 } // namespace gmx::internal
416 * Clears the device buffer asynchronously.
418 * \tparam ValueType Raw value type of the \p buffer.
419 * \param[in,out] buffer Pointer to the device-side buffer.
420 * \param[in] startingOffset Offset (in values) at the device-side buffer to start clearing at.
421 * \param[in] numValues Number of values to clear.
422 * \param[in] deviceStream GPU stream.
424 template<typename ValueType>
425 void clearDeviceBufferAsync(DeviceBuffer<ValueType>* buffer,
426 size_t startingOffset,
428 const DeviceStream& deviceStream)
434 GMX_ASSERT(buffer, "needs a buffer pointer");
436 GMX_ASSERT(checkDeviceBuffer(*buffer, startingOffset + numValues),
437 "buffer too small or not initialized");
439 cl::sycl::buffer<ValueType>& syclBuffer = *(buffer->buffer_);
441 gmx::internal::fillSyclBufferWithNull<ValueType>(
442 syclBuffer, startingOffset, numValues, deviceStream.stream());
445 /*! \brief Create a texture object for an array of type ValueType.
447 * Creates the device buffer and copies read-only data for an array of type ValueType.
448 * Like OpenCL, does not really do anything with textures, simply creates a buffer
449 * and initializes it.
451 * \tparam ValueType Raw data type.
453 * \param[out] deviceBuffer Device buffer to store data in.
454 * \param[in] hostBuffer Host buffer to get date from.
455 * \param[in] numValues Number of elements in the buffer.
456 * \param[in] deviceContext GPU device context.
458 template<typename ValueType>
459 void initParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer,
460 DeviceTexture* /* deviceTexture */,
461 const ValueType* hostBuffer,
463 const DeviceContext& deviceContext)
465 GMX_ASSERT(hostBuffer, "Host buffer should be specified.");
466 GMX_ASSERT(deviceBuffer, "Device buffer should be specified.");
468 /* Constructing buffer with cl::sycl::buffer(T* data, size_t size) will take ownership
469 * of this memory region making it unusable, which might lead to side-effects.
470 * On the other hand, cl::sycl::buffer(InputIterator<T> begin, InputIterator<T> end) will
471 * initialize the buffer without affecting ownership of the memory, although
472 * it will consume extra memory on host. */
473 const cl::sycl::property_list bufferProperties{ cl::sycl::property::buffer::context_bound(
474 deviceContext.context()) };
475 deviceBuffer->buffer_.reset(new ClSyclBufferWrapper<ValueType>(
476 hostBuffer, hostBuffer + numValues, bufferProperties));
479 /*! \brief Release the OpenCL device buffer.
481 * \tparam ValueType Raw data type.
483 * \param[in,out] deviceBuffer Device buffer to store data in.
485 template<typename ValueType>
486 void destroyParamLookupTable(DeviceBuffer<ValueType>* deviceBuffer, DeviceTexture& /* deviceTexture */)
488 deviceBuffer->buffer_.reset(nullptr);
491 #endif // GMX_GPU_UTILS_DEVICEBUFFER_SYCL_H