Draft: Fix compilation
[alexxy/gromacs.git] / src / gromacs / hardware / device_management_ocl.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016, by the GROMACS development team.
5  * Copyright (c) 2017,2018,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.
9  *
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.
14  *
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.
19  *
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.
24  *
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.
32  *
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.
35  */
36 /*! \internal \file
37  *  \brief Defines the OpenCL implementations of the device management.
38  *
39  *  \author Anca Hamuraru <anca@streamcomputing.eu>
40  *  \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
41  *  \author Teemu Virolainen <teemu@streamcomputing.eu>
42  *  \author Mark Abraham <mark.j.abraham@gmail.com>
43  *  \author Szilárd Páll <pall.szilard@gmail.com>
44  *  \author Artem Zhmurov <zhmurov@gmail.com>
45  *
46  * \ingroup module_hardware
47  */
48 #include "gmxpre.h"
49
50 #include "config.h"
51
52 #include "gromacs/gpu_utils/oclraii.h"
53 #include "gromacs/gpu_utils/oclutils.h"
54 #include "gromacs/hardware/device_management.h"
55 #include "gromacs/utility/fatalerror.h"
56 #include "gromacs/utility/smalloc.h"
57 #include "gromacs/utility/stringutil.h"
58
59 #include "device_information.h"
60
61 namespace gmx
62 {
63
64 /*! \brief Returns an DeviceVendor value corresponding to the input OpenCL vendor name.
65  *
66  *  \returns               DeviceVendor value for the input vendor name
67  */
68 static DeviceVendor getDeviceVendor(const char* vendorName)
69 {
70     if (vendorName)
71     {
72         if (strstr(vendorName, "NVIDIA"))
73         {
74             return DeviceVendor::Nvidia;
75         }
76         else if (strstr(vendorName, "AMD") || strstr(vendorName, "Advanced Micro Devices"))
77         {
78             return DeviceVendor::Amd;
79         }
80         else if (strstr(vendorName, "Intel"))
81         {
82             return DeviceVendor::Intel;
83         }
84     }
85     return DeviceVendor::Unknown;
86 }
87
88 /*! \brief Return true if executing on compatible OS for AMD OpenCL.
89  *
90  * This is assumed to be true for OS X version of at least 10.10.4 and
91  * all other OS flavors.
92  *
93  * \return true if version is 14.4 or later (= OS X version 10.10.4),
94  *         or OS is not Darwin.
95  */
96 static bool runningOnCompatibleOSForAmd()
97 {
98 #ifdef __APPLE__
99     int    mib[2];
100     char   kernelVersion[256];
101     size_t len = sizeof(kernelVersion);
102
103     mib[0] = CTL_KERN;
104
105     int major = strtod(kernelVersion, NULL);
106     int minor = strtod(strchr(kernelVersion, '.') + 1, NULL);
107
108     // Kernel 14.4 corresponds to OS X 10.10.4
109     return (major > 14 || (major == 14 && minor >= 4));
110 #else
111     return true;
112 #endif
113 }
114
115 /*! \brief Return true if executing on compatible GPU for NVIDIA OpenCL.
116  *
117  * There are known issues with OpenCL when running on NVIDIA Volta or newer (CC 7+).
118  * As a workaround, we recommend using CUDA on such hardware.
119  *
120  * This function relies on cl_nv_device_attribute_query. In case it's not functioning properly,
121  * we trust the user and mark the device as compatible.
122  *
123  * \return true if running on Pascal (CC 6.x) or older, or if we can not determine device generation.
124  */
125 static bool runningOnCompatibleHWForNvidia(const DeviceInformation& deviceInfo)
126 {
127     // The macro is defined in Intel's and AMD's headers, but it's not strictly required to be there.
128 #ifndef CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV
129     return true;
130 #else
131     static const unsigned int ccMajorBad = 7; // Volta and Turing
132     unsigned int              ccMajor;
133     cl_device_id              devId = deviceInfo.oclDeviceId;
134     const cl_int              err   = clGetDeviceInfo(devId, CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV,
135                                        sizeof(ccMajor), &ccMajor, nullptr);
136     if (err != CL_SUCCESS)
137     {
138         return true; // Err on a side of trusting the user to know what they are doing.
139     }
140     return ccMajor < ccMajorBad;
141 #endif
142 }
143
144 /*!
145  * \brief Checks that device \c deviceInfo is compatible with GROMACS.
146  *
147  *  Vendor and OpenCL version support checks are executed an the result
148  *  of these returned.
149  *
150  * \param[in]  deviceInfo  The device info pointer.
151  * \returns                The status enumeration value for the checked device:
152  */
153 static DeviceStatus isDeviceFunctional(const DeviceInformation& deviceInfo)
154 {
155     if (getenv("GMX_GPU_DISABLE_COMPATIBILITY_CHECK") != nullptr)
156     {
157         // Assume the device is compatible because checking has been disabled.
158         return DeviceStatus::Compatible;
159     }
160     if (getenv("GMX_OCL_DISABLE_COMPATIBILITY_CHECK") != nullptr)
161     {
162         fprintf(stderr,
163                 "Environment variable GMX_OCL_DISABLE_COMPATIBILITY_CHECK is deprecated and will "
164                 "be removed in release 2022. Please use GMX_GPU_DISABLE_COMPATIBILITY_CHECK "
165                 "instead.\n");
166         return DeviceStatus::Compatible;
167     }
168
169     // OpenCL device version check, ensure >= REQUIRED_OPENCL_MIN_VERSION
170     constexpr unsigned int minVersionMajor = REQUIRED_OPENCL_MIN_VERSION_MAJOR;
171     constexpr unsigned int minVersionMinor = REQUIRED_OPENCL_MIN_VERSION_MINOR;
172
173     // Based on the OpenCL spec we're checking the version supported by
174     // the device which has the following format:
175     //      OpenCL<space><major_version.minor_version><space><vendor-specific information>
176     unsigned int deviceVersionMinor, deviceVersionMajor;
177     const int    valuesScanned = std::sscanf(deviceInfo.device_version, "OpenCL %u.%u",
178                                           &deviceVersionMajor, &deviceVersionMinor);
179     const bool   versionLargeEnough =
180             ((valuesScanned == 2)
181              && ((deviceVersionMajor > minVersionMajor)
182                  || (deviceVersionMajor == minVersionMajor && deviceVersionMinor >= minVersionMinor)));
183     if (!versionLargeEnough)
184     {
185         return DeviceStatus::Incompatible;
186     }
187
188     /* Only AMD, Intel, and NVIDIA GPUs are supported for now */
189     switch (deviceInfo.deviceVendor)
190     {
191         case DeviceVendor::Nvidia:
192             return runningOnCompatibleHWForNvidia(deviceInfo) ? DeviceStatus::Compatible
193                                                               : DeviceStatus::IncompatibleNvidiaVolta;
194         case DeviceVendor::Amd:
195             return runningOnCompatibleOSForAmd() ? DeviceStatus::Compatible : DeviceStatus::Incompatible;
196         case DeviceVendor::Intel:
197             return GMX_OPENCL_NB_CLUSTER_SIZE == 4 ? DeviceStatus::Compatible
198                                                    : DeviceStatus::IncompatibleClusterSize;
199         default: return DeviceStatus::Incompatible;
200     }
201 }
202
203 /*! \brief Make an error string following an OpenCL API call.
204  *
205  *  It is meant to be called with \p status != CL_SUCCESS, but it will
206  *  work correctly even if it is called with no OpenCL failure.
207  *
208  * \todo Make use of this function more.
209  *
210  * \param[in]  message  Supplies context, e.g. the name of the API call that returned the error.
211  * \param[in]  status   OpenCL API status code
212  * \returns             A string describing the OpenCL error.
213  */
214 inline std::string makeOpenClInternalErrorString(const char* message, cl_int status)
215 {
216     if (message != nullptr)
217     {
218         return gmx::formatString("%s did %ssucceed %d: %s", message,
219                                  ((status != CL_SUCCESS) ? "not " : ""), status,
220                                  ocl_get_error_string(status).c_str());
221     }
222     else
223     {
224         return gmx::formatString("%sOpenCL error encountered %d: %s",
225                                  ((status != CL_SUCCESS) ? "" : "No "), status,
226                                  ocl_get_error_string(status).c_str());
227     }
228 }
229
230 /*!
231  * \brief Checks that device \c deviceInfo is sane (ie can run a kernel).
232  *
233  * Compiles and runs a dummy kernel to determine whether the given
234  * OpenCL device functions properly.
235  *
236  *
237  * \param[in]  deviceInfo      The device info pointer.
238  * \param[out] errorMessage    An error message related to a failing OpenCL API call.
239  * \throws     std::bad_alloc  When out of memory.
240  * \returns                    Whether the device passed sanity checks
241  */
242 static bool isDeviceFunctional(const DeviceInformation& deviceInfo, std::string* errorMessage)
243 {
244     cl_context_properties properties[] = {
245         CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(deviceInfo.oclPlatformId), 0
246     };
247     // uncrustify spacing
248
249     cl_int    status;
250     auto      deviceId = deviceInfo.oclDeviceId;
251     ClContext context(clCreateContext(properties, 1, &deviceId, nullptr, nullptr, &status));
252     if (status != CL_SUCCESS)
253     {
254         errorMessage->assign(makeOpenClInternalErrorString("clCreateContext", status));
255         return false;
256     }
257     ClCommandQueue commandQueue(clCreateCommandQueue(context, deviceId, 0, &status));
258     if (status != CL_SUCCESS)
259     {
260         errorMessage->assign(makeOpenClInternalErrorString("clCreateCommandQueue", status));
261         return false;
262     }
263
264     // Some compilers such as Apple's require kernel functions to have at least one argument
265     const char* lines[] = { "__kernel void dummyKernel(__global void* input){}" };
266     ClProgram   program(clCreateProgramWithSource(context, 1, lines, nullptr, &status));
267     if (status != CL_SUCCESS)
268     {
269         errorMessage->assign(makeOpenClInternalErrorString("clCreateProgramWithSource", status));
270         return false;
271     }
272
273     if ((status = clBuildProgram(program, 0, nullptr, nullptr, nullptr, nullptr)) != CL_SUCCESS)
274     {
275         errorMessage->assign(makeOpenClInternalErrorString("clBuildProgram", status));
276         return false;
277     }
278
279     ClKernel kernel(clCreateKernel(program, "dummyKernel", &status));
280     if (status != CL_SUCCESS)
281     {
282         errorMessage->assign(makeOpenClInternalErrorString("clCreateKernel", status));
283         return false;
284     }
285
286     clSetKernelArg(kernel, 0, sizeof(void*), nullptr);
287
288     const size_t localWorkSize = 1, globalWorkSize = 1;
289     if ((status = clEnqueueNDRangeKernel(commandQueue, kernel, 1, nullptr, &globalWorkSize,
290                                          &localWorkSize, 0, nullptr, nullptr))
291         != CL_SUCCESS)
292     {
293         errorMessage->assign(makeOpenClInternalErrorString("clEnqueueNDRangeKernel", status));
294         return false;
295     }
296     return true;
297 }
298
299 /*! \brief Check whether the \c ocl_gpu_device is suitable for use by mdrun
300  *
301  * Runs sanity checks: checking that the runtime can compile a dummy kernel
302  * and this can be executed;
303  * Runs compatibility checks verifying the device OpenCL version requirement
304  * and vendor/OS support.
305  *
306  * \param[in]  deviceId      The runtime-reported numeric ID of the device.
307  * \param[in]  deviceInfo    The device info pointer.
308  * \returns  A DeviceStatus to indicate if the GPU device is supported and if it was able to run
309  *           basic functionality checks.
310  */
311 static DeviceStatus checkGpu(size_t deviceId, const DeviceInformation& deviceInfo)
312 {
313
314     DeviceStatus supportStatus = isDeviceFunctional(deviceInfo);
315     if (supportStatus != DeviceStatus::Compatible)
316     {
317         return supportStatus;
318     }
319
320     std::string errorMessage;
321     if (!isDeviceFunctional(deviceInfo, &errorMessage))
322     {
323         gmx_warning("While sanity checking device #%zu, %s", deviceId, errorMessage.c_str());
324         return DeviceStatus::NonFunctional;
325     }
326
327     return DeviceStatus::Compatible;
328 }
329
330 } // namespace gmx
331
332 bool isDeviceDetectionFunctional(std::string* errorMessage)
333 {
334     cl_uint numPlatforms;
335     cl_int  status = clGetPlatformIDs(0, nullptr, &numPlatforms);
336     GMX_ASSERT(status != CL_INVALID_VALUE, "Incorrect call of clGetPlatformIDs detected");
337 #ifdef cl_khr_icd
338     if (status == CL_PLATFORM_NOT_FOUND_KHR)
339     {
340         // No valid ICDs found
341         if (errorMessage != nullptr)
342         {
343             errorMessage->assign("No valid OpenCL driver found");
344         }
345         return false;
346     }
347 #endif
348     GMX_RELEASE_ASSERT(
349             status == CL_SUCCESS,
350             gmx::formatString("An unexpected value was returned from clGetPlatformIDs %d: %s",
351                               status, ocl_get_error_string(status).c_str())
352                     .c_str());
353     bool foundPlatform = (numPlatforms > 0);
354     if (!foundPlatform && errorMessage != nullptr)
355     {
356         errorMessage->assign("No OpenCL platforms found even though the driver was valid");
357     }
358     return foundPlatform;
359 }
360
361 std::vector<std::unique_ptr<DeviceInformation>> findDevices()
362 {
363     cl_uint         ocl_platform_count;
364     cl_platform_id* ocl_platform_ids;
365     cl_device_type  req_dev_type = CL_DEVICE_TYPE_GPU;
366
367     ocl_platform_ids = nullptr;
368
369     if (getenv("GMX_OCL_FORCE_CPU") != nullptr)
370     {
371         req_dev_type = CL_DEVICE_TYPE_CPU;
372     }
373
374     int                                             numDevices = 0;
375     std::vector<std::unique_ptr<DeviceInformation>> deviceInfoList(0);
376
377     while (true)
378     {
379         cl_int status = clGetPlatformIDs(0, nullptr, &ocl_platform_count);
380         if (CL_SUCCESS != status)
381         {
382             GMX_THROW(gmx::InternalError(
383                     gmx::formatString("An unexpected value %d was returned from clGetPlatformIDs: ", status)
384                     + ocl_get_error_string(status)));
385         }
386
387         if (1 > ocl_platform_count)
388         {
389             // TODO this should have a descriptive error message that we only support one OpenCL platform
390             break;
391         }
392
393         snew(ocl_platform_ids, ocl_platform_count);
394
395         status = clGetPlatformIDs(ocl_platform_count, ocl_platform_ids, nullptr);
396         if (CL_SUCCESS != status)
397         {
398             GMX_THROW(gmx::InternalError(
399                     gmx::formatString("An unexpected value %d was returned from clGetPlatformIDs: ", status)
400                     + ocl_get_error_string(status)));
401         }
402
403         for (unsigned int i = 0; i < ocl_platform_count; i++)
404         {
405             cl_uint ocl_device_count;
406
407             /* If requesting req_dev_type devices fails, just go to the next platform */
408             if (CL_SUCCESS != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, 0, nullptr, &ocl_device_count))
409             {
410                 continue;
411             }
412
413             if (1 <= ocl_device_count)
414             {
415                 numDevices += ocl_device_count;
416             }
417         }
418
419         if (1 > numDevices)
420         {
421             break;
422         }
423
424         deviceInfoList.resize(numDevices);
425
426         {
427             int           device_index;
428             cl_device_id* ocl_device_ids;
429
430             snew(ocl_device_ids, numDevices);
431             device_index = 0;
432
433             for (unsigned int i = 0; i < ocl_platform_count; i++)
434             {
435                 cl_uint ocl_device_count;
436
437                 /* If requesting req_dev_type devices fails, just go to the next platform */
438                 if (CL_SUCCESS
439                     != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, numDevices, ocl_device_ids,
440                                       &ocl_device_count))
441                 {
442                     continue;
443                 }
444
445                 if (1 > ocl_device_count)
446                 {
447                     break;
448                 }
449
450                 for (unsigned int j = 0; j < ocl_device_count; j++)
451                 {
452                     deviceInfoList[device_index] = std::make_unique<DeviceInformation>();
453
454                     deviceInfoList[device_index]->id = device_index;
455
456                     deviceInfoList[device_index]->oclPlatformId = ocl_platform_ids[i];
457                     deviceInfoList[device_index]->oclDeviceId   = ocl_device_ids[j];
458
459                     deviceInfoList[device_index]->device_name[0] = 0;
460                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_NAME,
461                                     sizeof(deviceInfoList[device_index]->device_name),
462                                     deviceInfoList[device_index]->device_name, nullptr);
463
464                     deviceInfoList[device_index]->device_version[0] = 0;
465                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VERSION,
466                                     sizeof(deviceInfoList[device_index]->device_version),
467                                     deviceInfoList[device_index]->device_version, nullptr);
468
469                     deviceInfoList[device_index]->vendorName[0] = 0;
470                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VENDOR,
471                                     sizeof(deviceInfoList[device_index]->vendorName),
472                                     deviceInfoList[device_index]->vendorName, nullptr);
473
474                     deviceInfoList[device_index]->compute_units = 0;
475                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_COMPUTE_UNITS,
476                                     sizeof(deviceInfoList[device_index]->compute_units),
477                                     &(deviceInfoList[device_index]->compute_units), nullptr);
478
479                     deviceInfoList[device_index]->adress_bits = 0;
480                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_ADDRESS_BITS,
481                                     sizeof(deviceInfoList[device_index]->adress_bits),
482                                     &(deviceInfoList[device_index]->adress_bits), nullptr);
483
484                     deviceInfoList[device_index]->deviceVendor =
485                             gmx::getDeviceVendor(deviceInfoList[device_index]->vendorName);
486
487                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_WORK_ITEM_SIZES, 3 * sizeof(size_t),
488                                     &deviceInfoList[device_index]->maxWorkItemSizes, nullptr);
489
490                     clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t),
491                                     &deviceInfoList[device_index]->maxWorkGroupSize, nullptr);
492
493                     deviceInfoList[device_index]->status =
494                             gmx::checkGpu(device_index, *deviceInfoList[device_index]);
495
496                     device_index++;
497                 }
498             }
499
500             numDevices = device_index;
501
502             /* Dummy sort of devices -  AMD first, then NVIDIA, then Intel */
503             // TODO: Sort devices based on performance.
504             if (0 < numDevices)
505             {
506                 int last = -1;
507                 for (int i = 0; i < numDevices; i++)
508                 {
509                     if (deviceInfoList[i]->deviceVendor == DeviceVendor::Amd)
510                     {
511                         last++;
512
513                         if (last < i)
514                         {
515                             std::swap(deviceInfoList[i], deviceInfoList[last]);
516                         }
517                     }
518                 }
519
520                 /* if more than 1 device left to be sorted */
521                 if ((numDevices - 1 - last) > 1)
522                 {
523                     for (int i = 0; i < numDevices; i++)
524                     {
525                         if (deviceInfoList[i]->deviceVendor == DeviceVendor::Nvidia)
526                         {
527                             last++;
528
529                             if (last < i)
530                             {
531                                 std::swap(deviceInfoList[i], deviceInfoList[last]);
532                             }
533                         }
534                     }
535                 }
536             }
537
538             sfree(ocl_device_ids);
539         }
540
541         break;
542     }
543
544     sfree(ocl_platform_ids);
545     return deviceInfoList;
546 }
547
548 void setActiveDevice(const DeviceInformation& deviceInfo)
549 {
550     // If the device is NVIDIA, for safety reasons we disable the JIT
551     // caching as this is known to be broken at least until driver 364.19;
552     // the cache does not always get regenerated when the source code changes,
553     // e.g. if the path to the kernel sources remains the same
554
555     if (deviceInfo.deviceVendor == DeviceVendor::Nvidia)
556     {
557         // Ignore return values, failing to set the variable does not mean
558         // that something will go wrong later.
559 #ifdef _MSC_VER
560         _putenv("CUDA_CACHE_DISABLE=1");
561 #else
562         // Don't override, maybe a dev is testing.
563         setenv("CUDA_CACHE_DISABLE", "1", 0);
564 #endif
565     }
566 }
567
568 void releaseDevice(DeviceInformation* /* deviceInfo */) {}
569
570 std::string getDeviceInformationString(const DeviceInformation& deviceInfo)
571 {
572     bool gpuExists = (deviceInfo.status != DeviceStatus::Nonexistent
573                       && deviceInfo.status != DeviceStatus::NonFunctional);
574
575     if (!gpuExists)
576     {
577         return gmx::formatString("#%d: %s, status: %s", deviceInfo.id, "N/A",
578                                  c_deviceStateString[deviceInfo.status]);
579     }
580     else
581     {
582         return gmx::formatString("#%d: name: %s, vendor: %s, device version: %s, status: %s",
583                                  deviceInfo.id, deviceInfo.device_name, deviceInfo.vendorName,
584                                  deviceInfo.device_version, c_deviceStateString[deviceInfo.status]);
585     }
586 }