2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2014,2015,2016,2017,2018 by the GROMACS development team.
5 * Copyright (c) 2019,2020, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
36 /*! \libinternal \file
37 * \brief Declare utility routines for OpenCL
39 * \author Anca Hamuraru <anca@streamcomputing.eu>
42 #ifndef GMX_GPU_UTILS_OCLUTILS_H
43 #define GMX_GPU_UTILS_OCLUTILS_H
47 #include "gromacs/gpu_utils/gmxopencl.h"
48 #include "gromacs/gpu_utils/gputraits_ocl.h"
49 #include "gromacs/utility/exceptions.h"
50 #include "gromacs/utility/gmxassert.h"
52 enum class GpuApiCallBehavior;
54 /*! \brief OpenCL vendor IDs */
57 OCL_VENDOR_NVIDIA = 0,
64 * \brief OpenCL GPU device identificator
66 * An OpenCL device is identified by its ID.
67 * The platform ID is also included for caching reasons.
71 cl_platform_id ocl_platform_id; /**< Platform ID */
72 cl_device_id ocl_device_id; /**< Device ID */
76 * \brief OpenCL device information.
78 * The OpenCL device information is queried and set at detection and contains
79 * both information about the device/hardware returned by the runtime as well
80 * as additional data like support status.
82 struct gmx_device_info_t
84 ocl_gpu_id_t ocl_gpu_id; /**< device ID assigned at detection */
85 char device_name[256]; /**< device name */
86 char device_version[256]; /**< device version */
87 char device_vendor[256]; /**< device vendor */
88 int compute_units; /**< number of compute units */
89 int adress_bits; /**< number of adress bits the device is capable of */
90 int stat; /**< device status takes values of e_gpu_detect_res_t */
91 ocl_vendor_id_t vendor_e; /**< device vendor as defined by ocl_vendor_id_t */
92 size_t maxWorkItemSizes[3]; /**< workgroup size limits (CL_DEVICE_MAX_WORK_ITEM_SIZES) */
93 size_t maxWorkGroupSize; /**< workgroup total size limit (CL_DEVICE_MAX_WORK_GROUP_SIZE) */
97 * \brief OpenCL GPU runtime data
99 * The device runtime data is meant to hold objects associated with a GROMACS rank's
100 * (thread or process) use of a single device (multiple devices per rank is not
101 * implemented). These objects should be constructed at ther point where a device
102 * dets assigned to a rank and released at when this assignment is no longer valid
103 * (i.e. at cleanup in the current implementation).
106 struct gmx_device_runtime_data_t
108 cl_context context; /**< OpenCL context */
109 cl_program program; /**< OpenCL program */
112 /*! \brief Launches synchronous or asynchronous device to host memory copy.
114 * If copy_event is not NULL, on return it will contain an event object
115 * identifying this particular device to host operation. The event can further
116 * be used to queue a wait for this operation or to query profiling information.
118 int ocl_copy_D2H(void* h_dest,
122 GpuApiCallBehavior transferKind,
123 cl_command_queue command_queue,
124 cl_event* copy_event);
127 /*! \brief Launches asynchronous device to host memory copy. */
128 int ocl_copy_D2H_async(void* h_dest,
132 cl_command_queue command_queue,
133 cl_event* copy_event);
135 /*! \brief Launches synchronous or asynchronous host to device memory copy.
137 * If copy_event is not NULL, on return it will contain an event object
138 * identifying this particular host to device operation. The event can further
139 * be used to queue a wait for this operation or to query profiling information.
141 int ocl_copy_H2D(cl_mem d_dest,
145 GpuApiCallBehavior transferKind,
146 cl_command_queue command_queue,
147 cl_event* copy_event);
149 /*! \brief Launches asynchronous host to device memory copy. */
150 int ocl_copy_H2D_async(cl_mem d_dest,
154 cl_command_queue command_queue,
155 cl_event* copy_event);
157 /*! \brief Launches synchronous host to device memory copy. */
158 int ocl_copy_H2D_sync(cl_mem d_dest, const void* h_src, size_t offset, size_t bytes, cl_command_queue command_queue);
160 /*! \brief Allocate host memory in malloc style */
161 void pmalloc(void** h_ptr, size_t nbytes);
163 /*! \brief Free host memory in malloc style */
164 void pfree(void* h_ptr);
166 /*! \brief Convert error code to diagnostic string */
167 std::string ocl_get_error_string(cl_int error);
169 /*! \brief Calls clFinish() in the stream \p s.
171 * \param[in] s stream to synchronize with
173 static inline void gpuStreamSynchronize(cl_command_queue s)
175 cl_int cl_error = clFinish(s);
176 GMX_RELEASE_ASSERT(CL_SUCCESS == cl_error,
177 ("Error caught during clFinish:" + ocl_get_error_string(cl_error)).c_str());
180 //! A debug checker to track cl_events being released correctly
181 inline void ensureReferenceCount(const cl_event& event, unsigned int refCount)
184 cl_int clError = clGetEventInfo(event, CL_EVENT_REFERENCE_COUNT, sizeof(refCount), &refCount, nullptr);
185 GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
186 GMX_ASSERT(refCount == refCount, "Unexpected reference count");
188 GMX_UNUSED_VALUE(event);
189 GMX_UNUSED_VALUE(refCount);
193 /*! \brief Pretend to synchronize an OpenCL stream (dummy implementation).
195 * \param[in] s queue to check
197 * \returns True if all tasks enqueued in the stream \p s (at the time of this call) have completed.
199 static inline bool haveStreamTasksCompleted(cl_command_queue gmx_unused s)
201 GMX_RELEASE_ASSERT(false, "haveStreamTasksCompleted is not implemented for OpenCL");
205 /* Kernel launch helpers */
208 * A function for setting up a single OpenCL kernel argument.
209 * This is the tail of the compile-time recursive function below.
210 * It has to be seen by the compiler first.
211 * As NB kernels might be using dynamic local memory as the last argument,
212 * this function also manages that, using sharedMemorySize from \p config.
214 * \param[in] kernel Kernel function handle
215 * \param[in] config Kernel configuration for launching
216 * \param[in] argIndex Index of the current argument
218 void inline prepareGpuKernelArgument(cl_kernel kernel, const KernelLaunchConfig& config, size_t argIndex)
220 if (config.sharedMemorySize > 0)
222 cl_int gmx_used_in_debug clError =
223 clSetKernelArg(kernel, argIndex, config.sharedMemorySize, nullptr);
224 GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
229 * Compile-time recursive function for setting up a single OpenCL kernel argument.
230 * This function uses one kernel argument pointer \p argPtr to call clSetKernelArg(),
231 * and calls itself on the next argument, eventually calling the tail function above.
233 * \tparam CurrentArg Type of the current argument
234 * \tparam RemainingArgs Types of remaining arguments after the current one
235 * \param[in] kernel Kernel function handle
236 * \param[in] config Kernel configuration for launching
237 * \param[in] argIndex Index of the current argument
238 * \param[in] argPtr Pointer to the current argument
239 * \param[in] otherArgsPtrs Pack of pointers to arguments remaining to process after the current one
241 template<typename CurrentArg, typename... RemainingArgs>
242 void prepareGpuKernelArgument(cl_kernel kernel,
243 const KernelLaunchConfig& config,
245 const CurrentArg* argPtr,
246 const RemainingArgs*... otherArgsPtrs)
248 cl_int gmx_used_in_debug clError = clSetKernelArg(kernel, argIndex, sizeof(CurrentArg), argPtr);
249 GMX_ASSERT(CL_SUCCESS == clError, ocl_get_error_string(clError).c_str());
251 // Assert on types not allowed to be passed to a kernel
252 // (as per section 6.9 of the OpenCL spec).
253 static_assert(!std::is_same<CurrentArg, bool>::value && !std::is_same<CurrentArg, size_t>::value
254 && !std::is_same<CurrentArg, ptrdiff_t>::value
255 && !std::is_same<CurrentArg, intptr_t>::value
256 && !std::is_same<CurrentArg, uintptr_t>::value,
257 "Invalid type passed to OpenCL kernel functions (see OpenCL spec section 6.9).");
259 prepareGpuKernelArgument(kernel, config, argIndex + 1, otherArgsPtrs...);
263 * A wrapper function for setting up all the OpenCL kernel arguments.
264 * Calls the recursive functions above.
266 * \tparam Args Types of all the kernel arguments
267 * \param[in] kernel Kernel function handle
268 * \param[in] config Kernel configuration for launching
269 * \param[in] argsPtrs Pointers to all the kernel arguments
270 * \returns A handle for the prepared parameter pack to be used with launchGpuKernel() as the last argument
271 * - currently always nullptr for OpenCL, as it manages kernel/arguments association by itself.
273 template<typename... Args>
274 void* prepareGpuKernelArguments(cl_kernel kernel, const KernelLaunchConfig& config, const Args*... argsPtrs)
276 prepareGpuKernelArgument(kernel, config, 0, argsPtrs...);
280 /*! \brief Launches the OpenCL kernel and handles the errors.
282 * \param[in] kernel Kernel function handle
283 * \param[in] config Kernel configuration for launching
284 * \param[in] timingEvent Timing event, fetched from GpuRegionTimer
285 * \param[in] kernelName Human readable kernel description, for error handling only
286 * \throws gmx::InternalError on kernel launch failure
288 inline void launchGpuKernel(cl_kernel kernel,
289 const KernelLaunchConfig& config,
290 CommandEvent* timingEvent,
291 const char* kernelName,
292 const void* /*kernelArgs*/)
294 const int workDimensions = 3;
295 const size_t* globalWorkOffset = nullptr;
296 const size_t waitListSize = 0;
297 const cl_event* waitList = nullptr;
298 size_t globalWorkSize[3];
299 for (int i = 0; i < workDimensions; i++)
301 globalWorkSize[i] = config.gridSize[i] * config.blockSize[i];
303 cl_int clError = clEnqueueNDRangeKernel(config.stream, kernel, workDimensions, globalWorkOffset,
304 globalWorkSize, config.blockSize, waitListSize,
305 waitList, timingEvent);
306 if (CL_SUCCESS != clError)
308 const std::string errorMessage = "GPU kernel (" + std::string(kernelName)
309 + ") failed to launch: " + ocl_get_error_string(clError);
310 GMX_THROW(gmx::InternalError(errorMessage));