64e925b885036f74e01a9dd2049f2d790cbb5a9a
[alexxy/gromacs.git] / src / gromacs / gpu_utils / ocl_compiler.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,2021, 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 Define infrastructure for OpenCL JIT compilation for Gromacs
38  *
39  *  \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
40  *  \author Anca Hamuraru <anca@streamcomputing.eu>
41  *  \author Teemu Virolainen <teemu@streamcomputing.eu>
42  *  \author Mark Abraham <mark.j.abraham@gmail.com>
43  */
44
45 #include "gmxpre.h"
46
47 #include "ocl_compiler.h"
48
49 #include "config.h"
50
51 #include <cstdio>
52
53 #include <algorithm>
54 #include <string>
55 #include <vector>
56
57 #include "gromacs/gpu_utils/oclutils.h"
58 #include "gromacs/utility/cstringutil.h"
59 #include "gromacs/utility/exceptions.h"
60 #include "gromacs/utility/gmxassert.h"
61 #include "gromacs/utility/path.h"
62 #include "gromacs/utility/programcontext.h"
63 #include "gromacs/utility/smalloc.h"
64 #include "gromacs/utility/stringutil.h"
65 #include "gromacs/utility/textreader.h"
66 #include "gromacs/utility/unique_cptr.h"
67
68 #include "ocl_caching.h"
69
70 namespace gmx
71 {
72 namespace ocl
73 {
74
75 /*! \brief True if OpenCL binary caching is enabled.
76  *
77  *  Currently caching is disabled by default unless the env var override
78  *  is used until we resolve concurrency issues. */
79 static bool useBuildCache = getenv("GMX_OCL_GENCACHE") != nullptr;
80
81 /*! \brief Handles writing the OpenCL JIT compilation log to \c fplog.
82  *
83  * If \c fplog is non-null and either the \c GMX_OCL_DUMP_LOG environment
84  * variable is set or the compilation failed, then the OpenCL
85  * compilation log is written.
86  *
87  * \param fplog               Open file pointer to log file
88  * \param program             OpenCL program that was compiled
89  * \param deviceId            Id of the device for which compilation took place
90  * \param kernelFilename      File name containing the kernel
91  * \param preprocessorOptions String containing the preprocessor command-line options used for the
92  *                            build
93  * \param buildFailed         Whether the OpenCL build succeeded
94  *
95  * \throws std::bad_alloc if out of memory */
96 static void writeOclBuildLog(FILE*              fplog,
97                              cl_program         program,
98                              cl_device_id       deviceId,
99                              const std::string& kernelFilename,
100                              const std::string& preprocessorOptions,
101                              bool               buildFailed)
102 {
103     bool writeOutput = ((fplog != nullptr) && (buildFailed || (getenv("GMX_OCL_DUMP_LOG") != nullptr)));
104
105     if (!writeOutput)
106     {
107         return;
108     }
109
110     // Get build log string size
111     size_t buildLogSize;
112     cl_int cl_error =
113             clGetProgramBuildInfo(program, deviceId, CL_PROGRAM_BUILD_LOG, 0, nullptr, &buildLogSize);
114     if (cl_error != CL_SUCCESS)
115     {
116         GMX_THROW(InternalError("Could not get OpenCL program build log size, error was "
117                                 + ocl_get_error_string(cl_error)));
118     }
119
120     char*             buildLog = nullptr;
121     unique_cptr<char> buildLogGuard;
122     if (buildLogSize != 0)
123     {
124         /* Allocate memory to fit the build log,
125            it can be very large in case of errors */
126         snew(buildLog, buildLogSize);
127         buildLogGuard.reset(buildLog);
128
129         /* Get the actual compilation log */
130         cl_error = clGetProgramBuildInfo(
131                 program, deviceId, CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, nullptr);
132         if (cl_error != CL_SUCCESS)
133         {
134             GMX_THROW(InternalError("Could not get OpenCL program build log, error was "
135                                     + ocl_get_error_string(cl_error)));
136         }
137     }
138
139     std::string message;
140     if (buildFailed)
141     {
142         message += "Compilation of source file " + kernelFilename + " failed!\n";
143     }
144     else
145     {
146         message += "Compilation of source file " + kernelFilename + " was successful!\n";
147     }
148     message += "-- Used build options: " + preprocessorOptions + "\n";
149     message += "--------------LOG START---------------\n";
150     message += buildLog;
151     message += "---------------LOG END----------------\n";
152     ;
153
154     fputs(message.c_str(), fplog);
155 }
156
157 /*! \brief Construct compiler options string
158  *
159  * \param deviceVendor  Device vendor. Used to automatically enable some
160  *                      vendor-specific options.
161  * \return The string with the compiler options
162  */
163 static std::string selectCompilerOptions(DeviceVendor deviceVendor)
164 {
165     std::string compilerOptions;
166
167     if (getenv("GMX_OCL_NOOPT"))
168     {
169         compilerOptions += " -cl-opt-disable";
170     }
171
172     /* Fastmath improves performance on all supported arch,
173      * but is tends to cause problems on Intel (Issue #3898) */
174     if ((deviceVendor != DeviceVendor::Intel) && (getenv("GMX_OCL_DISABLE_FASTMATH") == nullptr))
175     {
176         compilerOptions += " -cl-fast-relaxed-math";
177
178         // Hint to the compiler that it can flush denorms to zero.
179         // In CUDA this is triggered by the -use_fast_math flag, equivalent with
180         // -cl-fast-relaxed-math, hence the inclusion on the conditional block.
181         compilerOptions += " -cl-denorms-are-zero";
182     }
183
184     if ((deviceVendor == DeviceVendor::Nvidia) && getenv("GMX_OCL_VERBOSE"))
185     {
186         compilerOptions += " -cl-nv-verbose";
187     }
188
189     if ((deviceVendor == DeviceVendor::Amd) && getenv("GMX_OCL_DUMP_INTERM_FILES"))
190     {
191         /* To dump OpenCL build intermediate files, caching must be off */
192         if (!useBuildCache)
193         {
194             compilerOptions += " -save-temps";
195         }
196     }
197
198     if (getenv("GMX_OCL_DEBUG"))
199     {
200         compilerOptions += " -g";
201     }
202
203     return compilerOptions;
204 }
205
206 /*! \brief Get the path to the folder storing an OpenCL source file.
207  *
208  * By default, this function constructs the full path to the OpenCL from
209  * the known location of the binary that is running, so that we handle
210  * both in-source and installed builds. The user can override this
211  * behavior by defining GMX_OCL_FILE_PATH environment variable.
212  *
213  * \param[in] sourceRelativePath    Relative path to the kernel or other file in the source tree,
214  *                                  from src, e.g. "gromacs/mdlib/nbnxn_ocl" for NB kernels.
215  * \return OS-normalized path string to the folder storing OpenCL source file
216  *
217  * \throws std::bad_alloc    if out of memory.
218  *         FileIOError  if GMX_OCL_FILE_PATH does not specify a readable path
219  */
220 static std::string getSourceRootPath(const std::string& sourceRelativePath)
221 {
222     std::string sourceRootPath;
223     /* Use GMX_OCL_FILE_PATH if the user has defined it */
224     const char* gmxOclFilePath = getenv("GMX_OCL_FILE_PATH");
225
226     if (gmxOclFilePath == nullptr)
227     {
228         /* Normal way of getting ocl_root_dir. First get the right
229            root path from the path to the binary that is running. */
230         InstallationPrefixInfo info           = getProgramContext().installationPrefix();
231         std::string            dataPathSuffix = (info.bSourceLayout ? "src" : GMX_INSTALL_OCLDIR);
232         sourceRootPath = Path::join(info.path, dataPathSuffix, sourceRelativePath);
233     }
234     else
235     {
236         if (!Directory::exists(gmxOclFilePath))
237         {
238             GMX_THROW(FileIOError(
239                     formatString("GMX_OCL_FILE_PATH must point to the directory where OpenCL"
240                                  "kernels are found, but '%s' does not exist",
241                                  gmxOclFilePath)));
242         }
243         sourceRootPath = Path::join(gmxOclFilePath, sourceRelativePath);
244     }
245
246     // Make sure we return an OS-correct path format
247     return Path::normalize(sourceRootPath);
248 }
249
250 size_t getKernelWarpSize(cl_kernel kernel, cl_device_id deviceId)
251 {
252     size_t warpSize = 0;
253     cl_int cl_error = clGetKernelWorkGroupInfo(
254             kernel, deviceId, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(warpSize), &warpSize, nullptr);
255     if (cl_error != CL_SUCCESS)
256     {
257         GMX_THROW(InternalError("Could not query OpenCL preferred workgroup size, error was "
258                                 + ocl_get_error_string(cl_error)));
259     }
260     if (warpSize == 0)
261     {
262         GMX_THROW(InternalError(formatString("Invalid OpenCL warp size encountered")));
263     }
264     return warpSize;
265 }
266
267 size_t getDeviceWarpSize(cl_context context, cl_device_id deviceId)
268 {
269     cl_int      cl_error;
270     const char* warpSizeKernel =
271             "__kernel void test(__global int* test){test[get_local_id(0)] = 0;}";
272     cl_program program = clCreateProgramWithSource(context, 1, &warpSizeKernel, nullptr, &cl_error);
273     if (cl_error != CL_SUCCESS)
274     {
275         GMX_THROW(InternalError("Could not create OpenCL program to determine warp size, error was "
276                                 + ocl_get_error_string(cl_error)));
277     }
278
279     cl_error = clBuildProgram(program, 0, nullptr, nullptr, nullptr, nullptr);
280     if (cl_error != CL_SUCCESS)
281     {
282         GMX_THROW(InternalError("Could not build OpenCL program to determine warp size, error was "
283                                 + ocl_get_error_string(cl_error)));
284     }
285
286     cl_kernel kernel = clCreateKernel(program, "test", &cl_error);
287     if (cl_error != CL_SUCCESS)
288     {
289         GMX_THROW(InternalError("Could not create OpenCL kernel to determine warp size, error was "
290                                 + ocl_get_error_string(cl_error)));
291     }
292
293     size_t warpSize = getKernelWarpSize(kernel, deviceId);
294
295     cl_error = clReleaseKernel(kernel);
296     if (cl_error != CL_SUCCESS)
297     {
298         GMX_THROW(InternalError("Could not release OpenCL warp-size kernel, error was "
299                                 + ocl_get_error_string(cl_error)));
300     }
301     cl_error = clReleaseProgram(program);
302     if (cl_error != CL_SUCCESS)
303     {
304         GMX_THROW(InternalError("Could not release OpenCL warp-size program, error was "
305                                 + ocl_get_error_string(cl_error)));
306     }
307
308     return warpSize;
309 }
310
311 /*! \brief Select a compilation-line define for a vendor-specific kernel choice from vendor id
312  *
313  * \param[in] deviceVendor Vendor id enumerator
314  *
315  * \return The appropriate compilation-line define
316  */
317 static std::string makeVendorFlavorChoice(DeviceVendor deviceVendor)
318 {
319     switch (deviceVendor)
320     {
321         case DeviceVendor::Amd: return "-D_AMD_SOURCE_";
322         case DeviceVendor::Nvidia: return "-D_NVIDIA_SOURCE_";
323         case DeviceVendor::Intel: return "-D_INTEL_SOURCE_";
324         default: return "";
325     }
326 }
327
328 /*! \brief Create include paths for kernel sources.
329  *
330  * All OpenCL kernel files are expected to be stored in one single folder.
331  *
332  * \throws std::bad_alloc  if out of memory.
333  */
334 static std::string makeKernelIncludePathOption(const std::string& unescapedKernelRootPath)
335 {
336     std::string includePathOption;
337
338     /* Apple does not seem to accept the quoted include paths other
339      * OpenCL implementations are happy with. Since the standard still says
340      * it should be quoted, we handle Apple as a special case.
341      */
342 #ifdef __APPLE__
343     includePathOption += "-I";
344
345     // Prepend all the spaces with a backslash
346     for (std::string::size_type i = 0; i < unescapedKernelRootPath.length(); i++)
347     {
348         if (unescapedKernelRootPath[i] == ' ')
349         {
350             includePathOption.push_back('\\');
351         }
352         includePathOption.push_back(unescapedKernelRootPath[i]);
353     }
354 #else
355     includePathOption += "-I\"" + unescapedKernelRootPath + "\"";
356 #endif
357
358     return includePathOption;
359 }
360
361 /*! \brief Replace duplicated spaces with a single one in string
362  *
363  * Only the first character will be kept for multiple adjacent characters that
364  * are both identical and where the first one returns true for isspace().
365  *
366  * \param str String that will be modified.
367  */
368 static void removeExtraSpaces(std::string* str)
369 {
370     GMX_RELEASE_ASSERT(str != nullptr, "A pointer to an actual string must be provided");
371     std::string::iterator newEnd = std::unique(
372             str->begin(), str->end(), [=](char a, char b) { return isspace(a) != 0 && (a == b); });
373     str->erase(newEnd, str->end());
374 }
375
376 /*! \brief Builds a string with build options for the OpenCL kernels
377  *
378  * \throws std::bad_alloc  if out of memory. */
379 static std::string makePreprocessorOptions(const std::string& kernelRootPath,
380                                            const std::string& includeRootPath,
381                                            size_t             warpSize,
382                                            DeviceVendor       deviceVendor,
383                                            const std::string& extraDefines)
384 {
385     std::string preprocessorOptions;
386
387     /* Compose the complete build options */
388     preprocessorOptions = formatString("-DWARP_SIZE_TEST=%d", static_cast<int>(warpSize));
389     preprocessorOptions += ' ';
390     preprocessorOptions += makeVendorFlavorChoice(deviceVendor);
391     preprocessorOptions += ' ';
392     preprocessorOptions += extraDefines;
393     preprocessorOptions += ' ';
394     preprocessorOptions += selectCompilerOptions(deviceVendor);
395     preprocessorOptions += ' ';
396     preprocessorOptions += makeKernelIncludePathOption(kernelRootPath);
397     preprocessorOptions += ' ';
398     preprocessorOptions += makeKernelIncludePathOption(includeRootPath);
399
400     // Mac OS (and maybe some other implementations) does not accept double spaces in options
401     removeExtraSpaces(&preprocessorOptions);
402
403     return preprocessorOptions;
404 }
405
406 cl_program compileProgram(FILE*              fplog,
407                           const std::string& kernelRelativePath,
408                           const std::string& kernelBaseFilename,
409                           const std::string& extraDefines,
410                           cl_context         context,
411                           cl_device_id       deviceId,
412                           DeviceVendor       deviceVendor)
413 {
414     cl_int cl_error;
415     // Let the kernel find include files from its module.
416     std::string kernelRootPath = getSourceRootPath(kernelRelativePath);
417     // Let the kernel find include files from other modules.
418     std::string rootPath = getSourceRootPath("");
419
420     GMX_RELEASE_ASSERT(fplog != nullptr, "Need a valid log file for building OpenCL programs");
421
422     /* Load OpenCL source files */
423     std::string kernelFilename = Path::join(kernelRootPath, kernelBaseFilename);
424
425     /* Make the build options */
426     std::string preprocessorOptions = makePreprocessorOptions(
427             kernelRootPath, rootPath, getDeviceWarpSize(context, deviceId), deviceVendor, extraDefines);
428
429     bool buildCacheWasRead = false;
430
431     std::string cacheFilename;
432     if (useBuildCache)
433     {
434         cacheFilename = makeBinaryCacheFilename(kernelBaseFilename, deviceId);
435     }
436
437     /* Create OpenCL program */
438     cl_program program = nullptr;
439     if (useBuildCache)
440     {
441         if (File::exists(cacheFilename, File::returnFalseOnError))
442         {
443             /* Check if there's a valid cache available */
444             try
445             {
446                 program           = makeProgramFromCache(cacheFilename, context, deviceId);
447                 buildCacheWasRead = true;
448             }
449             catch (FileIOError& e)
450             {
451                 // Failing to read from the cache is not a critical error
452                 formatExceptionMessageToFile(fplog, e);
453             }
454             fprintf(fplog,
455                     "OpenCL binary cache file %s is present, will load kernels.\n",
456                     cacheFilename.c_str());
457         }
458         else
459         {
460             fprintf(fplog,
461                     "No OpenCL binary cache file was present for %s, so will compile kernels "
462                     "normally.\n",
463                     kernelBaseFilename.c_str());
464         }
465     }
466     if (program == nullptr)
467     {
468         // Compile OpenCL program from source
469         std::string kernelSource = TextReader::readFileToString(kernelFilename);
470         if (kernelSource.empty())
471         {
472             GMX_THROW(FileIOError("Error loading OpenCL code " + kernelFilename));
473         }
474         const char* kernelSourcePtr  = kernelSource.c_str();
475         size_t      kernelSourceSize = kernelSource.size();
476         /* Create program from source code */
477         program = clCreateProgramWithSource(context, 1, &kernelSourcePtr, &kernelSourceSize, &cl_error);
478         if (cl_error != CL_SUCCESS)
479         {
480             GMX_THROW(InternalError("Could not create OpenCL program, error was "
481                                     + ocl_get_error_string(cl_error)));
482         }
483     }
484
485     /* Build the OpenCL program, keeping the status to potentially
486        write to the simulation log file. */
487     cl_int buildStatus =
488             clBuildProgram(program, 0, nullptr, preprocessorOptions.c_str(), nullptr, nullptr);
489
490     /* Write log first, and then throw exception that the user know what is
491        the issue even if the build fails. */
492     writeOclBuildLog(fplog, program, deviceId, kernelFilename, preprocessorOptions, buildStatus != CL_SUCCESS);
493
494     if (buildStatus != CL_SUCCESS)
495     {
496         GMX_THROW(InternalError("Could not build OpenCL program, error was "
497                                 + ocl_get_error_string(buildStatus)));
498     }
499
500     if (useBuildCache)
501     {
502         if (!buildCacheWasRead)
503         {
504             /* If OpenCL caching is ON, but the current cache is not
505                valid => update it */
506             try
507             {
508                 writeBinaryToCache(program, cacheFilename);
509             }
510             catch (GromacsException& e)
511             {
512                 // Failing to write the cache is not a critical error
513                 formatExceptionMessageToFile(fplog, e);
514             }
515         }
516     }
517     if ((deviceVendor == DeviceVendor::Nvidia) && getenv("GMX_OCL_DUMP_INTERM_FILES"))
518     {
519         /* If dumping intermediate files has been requested and this is an NVIDIA card
520            => write PTX to file */
521         char buffer[STRLEN];
522
523         cl_error = clGetDeviceInfo(deviceId, CL_DEVICE_NAME, sizeof(buffer), buffer, nullptr);
524         if (cl_error != CL_SUCCESS)
525         {
526             GMX_THROW(InternalError("Could not get OpenCL device info, error was "
527                                     + ocl_get_error_string(cl_error)));
528         }
529         std::string ptxFilename = buffer;
530         ptxFilename += ".ptx";
531
532         try
533         {
534             writeBinaryToCache(program, ptxFilename);
535         }
536         catch (GromacsException& e)
537         {
538             // Failing to write the cache is not a critical error
539             formatExceptionMessageToFile(fplog, e);
540         }
541     }
542
543     return program;
544 }
545
546 } // namespace ocl
547 } // namespace gmx