2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015,2016,2017,2018, 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.
36 * \brief Define infrastructure for OpenCL JIT compilation for Gromacs
38 * \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
39 * \author Anca Hamuraru <anca@streamcomputing.eu>
40 * \author Teemu Virolainen <teemu@streamcomputing.eu>
41 * \author Mark Abraham <mark.j.abraham@gmail.com>
46 #include "ocl_compiler.h"
56 #include "gromacs/gpu_utils/oclutils.h"
57 #include "gromacs/utility/cstringutil.h"
58 #include "gromacs/utility/exceptions.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/path.h"
61 #include "gromacs/utility/programcontext.h"
62 #include "gromacs/utility/smalloc.h"
63 #include "gromacs/utility/stringutil.h"
64 #include "gromacs/utility/textreader.h"
65 #include "gromacs/utility/unique_cptr.h"
67 #include "ocl_caching.h"
74 /*! \brief True if OpenCL binary caching is enabled.
76 * Currently caching is disabled by default unless the env var override
77 * is used until we resolve concurrency issues. */
78 static bool useBuildCache = getenv("GMX_OCL_GENCACHE") != nullptr;
80 /*! \brief Handles writing the OpenCL JIT compilation log to \c fplog.
82 * If \c fplog is non-null and either the GMX_OCL_DUMP_LOG environment
83 * variable is set or the compilation failed, then the OpenCL
84 * compilation log is written.
86 * \param fplog Open file pointer to log file
87 * \param program OpenCL program that was compiled
88 * \param deviceId Id of the device for which compilation took place
89 * \param kernelFilename File name containing the kernel
90 * \param preprocessorOptions String containing the preprocessor command-line options used for the build
91 * \param buildFailed Whether the OpenCL build succeeded
93 * \throws std::bad_alloc if out of memory */
95 writeOclBuildLog(FILE *fplog,
97 cl_device_id deviceId,
98 const std::string &kernelFilename,
99 const std::string &preprocessorOptions,
102 bool writeOutput = ((fplog != nullptr) &&
103 (buildFailed || (getenv("GMX_OCL_DUMP_LOG") != nullptr)));
110 // Get build log string size
112 cl_int cl_error = clGetProgramBuildInfo(program,
114 CL_PROGRAM_BUILD_LOG,
118 if (cl_error != CL_SUCCESS)
120 GMX_THROW(InternalError("Could not get OpenCL program build log size, error was " + ocl_get_error_string(cl_error)));
123 char *buildLog = nullptr;
124 unique_cptr<char> buildLogGuard;
125 if (buildLogSize != 0)
127 /* Allocate memory to fit the build log,
128 it can be very large in case of errors */
129 snew(buildLog, buildLogSize);
130 buildLogGuard.reset(buildLog);
132 /* Get the actual compilation log */
133 cl_error = clGetProgramBuildInfo(program,
135 CL_PROGRAM_BUILD_LOG,
139 if (cl_error != CL_SUCCESS)
141 GMX_THROW(InternalError("Could not get OpenCL program build log, error was " + ocl_get_error_string(cl_error)));
148 message += "Compilation of source file " + kernelFilename + " failed!\n";
152 message += "Compilation of source file " + kernelFilename + " was successful!\n";
154 message += "-- Used build options: " + preprocessorOptions + "\n";
155 message += "--------------LOG START---------------\n";
157 message += "---------------LOG END----------------\n";;
159 fputs(message.c_str(), fplog);
162 /*! \brief Construct compiler options string
164 * \param deviceVendorId Device vendor id. Used to
165 * automatically enable some vendor-specific options
166 * \return The string with the compiler options
169 selectCompilerOptions(ocl_vendor_id_t deviceVendorId)
171 std::string compilerOptions;
173 if (getenv("GMX_OCL_NOOPT") )
175 compilerOptions += " -cl-opt-disable";
178 /* Fastmath imprves performance on all supported arch */
179 if (getenv("GMX_OCL_DISABLE_FASTMATH") == nullptr)
181 compilerOptions += " -cl-fast-relaxed-math";
183 // Hint to the compiler that it can flush denorms to zero.
184 // In CUDA this is triggered by the -use_fast_math flag, equivalent with
185 // -cl-fast-relaxed-math, hence the inclusion on the conditional block.
186 compilerOptions += " -cl-denorms-are-zero";
189 if ((deviceVendorId == OCL_VENDOR_NVIDIA) && getenv("GMX_OCL_VERBOSE"))
191 compilerOptions += " -cl-nv-verbose";
194 if ((deviceVendorId == OCL_VENDOR_AMD) && getenv("GMX_OCL_DUMP_INTERM_FILES"))
196 /* To dump OpenCL build intermediate files, caching must be off */
199 compilerOptions += " -save-temps";
203 if (getenv("GMX_OCL_DEBUG"))
205 compilerOptions += " -g";
208 return compilerOptions;
211 /*! \brief Get the path to the folder storing an OpenCL source file.
213 * By default, this function constructs the full path to the OpenCL from
214 * the known location of the binary that is running, so that we handle
215 * both in-source and installed builds. The user can override this
216 * behavior by defining GMX_OCL_FILE_PATH environment variable.
218 * \param[in] sourceRelativePath Relative path to the kernel or other file in the source tree,
219 * e.g. "src/gromacs/mdlib/nbnxn_ocl" for NB kernels.
220 * \return OS-normalized path string to the folder storing OpenCL source file
222 * \throws std::bad_alloc if out of memory.
223 * FileIOError if GMX_OCL_FILE_PATH does not specify a readable path
226 getSourceRootPath(const std::string &sourceRelativePath)
228 std::string sourceRootPath;
229 /* Use GMX_OCL_FILE_PATH if the user has defined it */
230 const char *gmxOclFilePath = getenv("GMX_OCL_FILE_PATH");
232 if (gmxOclFilePath == nullptr)
234 /* Normal way of getting ocl_root_dir. First get the right
235 root path from the path to the binary that is running. */
236 InstallationPrefixInfo info = getProgramContext().installationPrefix();
237 std::string dataPathSuffix = (info.bSourceLayout ?
240 sourceRootPath = Path::join(info.path, dataPathSuffix);
244 if (!Directory::exists(gmxOclFilePath))
246 GMX_THROW(FileIOError(formatString("GMX_OCL_FILE_PATH must point to the directory where OpenCL"
247 "kernels are found, but '%s' does not exist", gmxOclFilePath)));
249 sourceRootPath = gmxOclFilePath;
252 // Make sure we return an OS-correct path format
253 return Path::normalize(sourceRootPath);
256 size_t getWarpSize(cl_context context, cl_device_id deviceId)
259 const char *warpSizeKernel = "__kernel void test(__global int* test){test[get_local_id(0)] = 0;}";
260 cl_program program = clCreateProgramWithSource(context, 1, &warpSizeKernel, nullptr, &cl_error);
261 if (cl_error != CL_SUCCESS)
263 GMX_THROW(InternalError("Could not create OpenCL program to determine warp size, error was " + ocl_get_error_string(cl_error)));
266 cl_error = clBuildProgram(program, 0, nullptr, nullptr, nullptr, nullptr);
267 if (cl_error != CL_SUCCESS)
269 GMX_THROW(InternalError("Could not build OpenCL program to determine warp size, error was " + ocl_get_error_string(cl_error)));
272 cl_kernel kernel = clCreateKernel(program, "test", &cl_error);
273 if (cl_error != CL_SUCCESS)
275 GMX_THROW(InternalError("Could not create OpenCL kernel to determine warp size, error was " + ocl_get_error_string(cl_error)));
279 cl_error = clGetKernelWorkGroupInfo(kernel, deviceId, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
280 sizeof(warpSize), &warpSize, nullptr);
281 if (cl_error != CL_SUCCESS)
283 GMX_THROW(InternalError("Could not measure OpenCL warp size, error was " + ocl_get_error_string(cl_error)));
287 GMX_THROW(InternalError(formatString("Did not measure a valid OpenCL warp size")));
290 cl_error = clReleaseKernel(kernel);
291 if (cl_error != CL_SUCCESS)
293 GMX_THROW(InternalError("Could not release OpenCL warp-size kernel, error was " + ocl_get_error_string(cl_error)));
295 cl_error = clReleaseProgram(program);
296 if (cl_error != CL_SUCCESS)
298 GMX_THROW(InternalError("Could not release OpenCL warp-size program, error was " + ocl_get_error_string(cl_error)));
304 /*! \brief Select a compilation-line define for a vendor-specific kernel choice from vendor id
306 * \param[in] vendorId Vendor id enumerator
308 * \return The appropriate compilation-line define
311 makeVendorFlavorChoice(ocl_vendor_id_t vendorId)
317 choice = "-D_AMD_SOURCE_";
319 case OCL_VENDOR_NVIDIA:
320 choice = "-D_NVIDIA_SOURCE_";
322 case OCL_VENDOR_INTEL:
323 choice = "-D_INTEL_SOURCE_";
332 /*! \brief Create include paths for kernel sources.
334 * All OpenCL kernel files are expected to be stored in one single folder.
336 * \throws std::bad_alloc if out of memory.
338 static std::string makeKernelIncludePathOption(const std::string &unescapedKernelRootPath)
340 std::string includePathOption;
342 /* Apple does not seem to accept the quoted include paths other
343 * OpenCL implementations are happy with. Since the standard still says
344 * it should be quoted, we handle Apple as a special case.
347 includePathOption += "-I";
349 // Prepend all the spaces with a backslash
350 for (std::string::size_type i = 0; i < unescapedKernelRootPath.length(); i++)
352 if (unescapedKernelRootPath[i] == ' ')
354 includePathOption.push_back('\\');
356 includePathOption.push_back(unescapedKernelRootPath[i]);
359 includePathOption += "-I\"" + unescapedKernelRootPath + "\"";
362 return includePathOption;
365 /*! \brief Replace duplicated spaces with a single one in string
367 * Only the first character will be kept for multiple adjacent characters that
368 * are both identical and where the first one returns true for isspace().
370 * \param str String that will be modified.
373 removeExtraSpaces(std::string *str)
375 GMX_RELEASE_ASSERT(str != nullptr, "A pointer to an actual string must be provided");
376 std::string::iterator newEnd =
377 std::unique( str->begin(), str->end(), [ = ](char a, char b){ return isspace(a) != 0 && (a == b); } );
378 str->erase(newEnd, str->end());
381 /*! \brief Builds a string with build options for the OpenCL kernels
383 * \throws std::bad_alloc if out of memory. */
385 makePreprocessorOptions(const std::string &kernelRootPath,
386 const std::string &includeRootPath,
388 ocl_vendor_id_t deviceVendorId,
389 const std::string &extraDefines)
391 std::string preprocessorOptions;
393 /* Compose the complete build options */
394 preprocessorOptions = formatString("-DWARP_SIZE_TEST=%d", static_cast<int>(warpSize));
395 preprocessorOptions += ' ';
396 preprocessorOptions += makeVendorFlavorChoice(deviceVendorId);
397 preprocessorOptions += ' ';
398 preprocessorOptions += extraDefines;
399 preprocessorOptions += ' ';
400 preprocessorOptions += selectCompilerOptions(deviceVendorId);
401 preprocessorOptions += ' ';
402 preprocessorOptions += makeKernelIncludePathOption(kernelRootPath);
403 preprocessorOptions += ' ';
404 preprocessorOptions += makeKernelIncludePathOption(includeRootPath);
406 // Mac OS (and maybe some other implementations) does not accept double spaces in options
407 removeExtraSpaces(&preprocessorOptions);
409 return preprocessorOptions;
413 compileProgram(FILE *fplog,
414 const std::string &kernelRelativePath,
415 const std::string &kernelBaseFilename,
416 const std::string &extraDefines,
418 cl_device_id deviceId,
419 ocl_vendor_id_t deviceVendorId)
422 std::string kernelRootPath = getSourceRootPath(kernelRelativePath);
423 std::string includeRootPath = getSourceRootPath("src");
425 GMX_RELEASE_ASSERT(fplog != nullptr, "Need a valid log file for building OpenCL programs");
427 /* Load OpenCL source files */
428 std::string kernelFilename = Path::join(kernelRootPath,
431 /* Make the build options */
432 std::string preprocessorOptions = makePreprocessorOptions(kernelRootPath,
434 getWarpSize(context, deviceId),
438 bool buildCacheWasRead = false;
440 std::string cacheFilename;
443 cacheFilename = makeBinaryCacheFilename(kernelBaseFilename, deviceId);
446 /* Create OpenCL program */
447 cl_program program = nullptr;
450 if (File::exists(cacheFilename, File::returnFalseOnError))
452 /* Check if there's a valid cache available */
455 program = makeProgramFromCache(cacheFilename, context, deviceId);
456 buildCacheWasRead = true;
458 catch (FileIOError &e)
460 // Failing to read from the cache is not a critical error
461 formatExceptionMessageToFile(fplog, e);
466 fprintf(fplog, "No OpenCL binary cache file was present, so will compile kernels normally.\n");
469 if (program == nullptr)
471 // Compile OpenCL program from source
472 std::string kernelSource = TextReader::readFileToString(kernelFilename);
473 if (kernelSource.empty())
475 GMX_THROW(FileIOError("Error loading OpenCL code " + kernelFilename));
477 const char *kernelSourcePtr = kernelSource.c_str();
478 size_t kernelSourceSize = kernelSource.size();
479 /* Create program from source code */
480 program = clCreateProgramWithSource(context,
485 if (cl_error != CL_SUCCESS)
487 GMX_THROW(InternalError("Could not create OpenCL program, error was " + ocl_get_error_string(cl_error)));
491 /* Build the OpenCL program, keeping the status to potentially
492 write to the simulation log file. */
493 cl_int buildStatus = clBuildProgram(program, 0, nullptr, preprocessorOptions.c_str(), nullptr, nullptr);
495 /* Write log first, and then throw exception that the user know what is
496 the issue even if the build fails. */
497 writeOclBuildLog(fplog,
502 buildStatus != CL_SUCCESS);
504 if (buildStatus != CL_SUCCESS)
506 GMX_THROW(InternalError("Could not build OpenCL program, error was " + ocl_get_error_string(buildStatus)));
511 if (!buildCacheWasRead)
513 /* If OpenCL caching is ON, but the current cache is not
514 valid => update it */
517 writeBinaryToCache(program, cacheFilename);
519 catch (GromacsException &e)
521 // Failing to write the cache is not a critical error
522 formatExceptionMessageToFile(fplog, e);
526 if ((OCL_VENDOR_NVIDIA == deviceVendorId) && getenv("GMX_OCL_DUMP_INTERM_FILES"))
528 /* If dumping intermediate files has been requested and this is an NVIDIA card
529 => write PTX to file */
532 cl_error = clGetDeviceInfo(deviceId, CL_DEVICE_NAME, sizeof(buffer), buffer, nullptr);
533 if (cl_error != CL_SUCCESS)
535 GMX_THROW(InternalError("Could not get OpenCL device info, error was " + ocl_get_error_string(cl_error)));
537 std::string ptxFilename = buffer;
538 ptxFilename += ".ptx";
542 writeBinaryToCache(program, ptxFilename);
544 catch (GromacsException &e)
546 // Failing to write the cache is not a critical error
547 formatExceptionMessageToFile(fplog, e);