18074556d69bd9eeb9025c4bac05e023dea70c4c
[alexxy/gromacs.git] / src / gromacs / gpu_utils / ocl_caching.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) 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 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_caching.h"
48
49 #include <assert.h>
50
51 #include <cctype>
52 #include <cstdio>
53
54 #include <algorithm>
55 #include <array>
56 #include <iterator>
57 #include <string>
58 #include <vector>
59
60 #include "gromacs/utility/exceptions.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"
66
67 namespace gmx
68 {
69 namespace ocl
70 {
71
72 std::string makeBinaryCacheFilename(const std::string& kernelFilename, cl_device_id deviceId)
73 {
74     // Note that the OpenCL API is defined in terms of bytes, and we
75     // assume that sizeof(char) is one byte.
76     std::array<char, 1024> deviceName;
77     size_t                 deviceNameLength;
78     cl_int                 cl_error = clGetDeviceInfo(deviceId, CL_DEVICE_NAME, deviceName.size(),
79                                       deviceName.data(), &deviceNameLength);
80     if (cl_error != CL_SUCCESS)
81     {
82         GMX_THROW(InternalError(formatString("Could not get OpenCL device name, error was %s",
83                                              ocl_get_error_string(cl_error).c_str())));
84     }
85
86     std::string cacheFilename = "OCL-cache";
87     /* remove the kernel source suffix */
88     cacheFilename += "_" + stripSuffixIfPresent(kernelFilename, ".cl") + "_";
89     /* We want a cache filename that's somewhat human readable, and
90        describes the device because it's based on the vendor's
91        information, but also always works as a filename. So we remove
92        characters that are commonly illegal in filenames (dot, slash),
93        or sometimes inconvenient (whitespace), or perhaps problematic
94        (symbols), by permitting only alphanumeric characters from the
95        current locale. We assume these work well enough in a
96        filename. */
97     std::copy_if(deviceName.begin(), deviceName.begin() + deviceNameLength,
98                  std::back_inserter(cacheFilename), isalnum);
99     cacheFilename += ".bin";
100
101     return cacheFilename;
102 }
103
104 cl_program makeProgramFromCache(const std::string& filename, cl_context context, cl_device_id deviceId)
105 {
106     // TODO all this file reading stuff should become gmx::BinaryReader
107     const auto f = create_unique_with_deleter(fopen(filename.c_str(), "rb"), fclose);
108     if (!f)
109     {
110         GMX_THROW(FileIOError("Failed to open binary cache file " + filename));
111     }
112
113     // TODO more stdio error handling
114     fseek(f.get(), 0, SEEK_END);
115     unsigned char*             binary;
116     unique_cptr<unsigned char> binaryGuard;
117     size_t                     fileSize = ftell(f.get());
118     snew(binary, fileSize);
119     binaryGuard.reset(binary);
120     fseek(f.get(), 0, SEEK_SET);
121     size_t readCount = fread(binary, 1, fileSize, f.get());
122
123     if (readCount != fileSize)
124     {
125         GMX_THROW(FileIOError("Failed to read binary cache file " + filename));
126     }
127
128     /* TODO If/when caching is re-enabled, compare current build
129      * options and code against the build options and the code
130      * corresponding to the cache. If any change is detected then the
131      * cache cannot be used.
132      *
133      * Also caching functionality will need full re-testing. */
134
135     /* Create program from pre-built binary */
136     cl_int     cl_error;
137     cl_program program = clCreateProgramWithBinary(context, 1, &deviceId, &fileSize,
138                                                    const_cast<const unsigned char**>(&binary),
139                                                    nullptr, &cl_error);
140     if (cl_error != CL_SUCCESS)
141     {
142         GMX_THROW(InternalError("Could not create OpenCL program, error was "
143                                 + ocl_get_error_string(cl_error)));
144     }
145
146     return program;
147 }
148
149 void writeBinaryToCache(cl_program program, const std::string& filename)
150 {
151     size_t fileSize;
152     cl_int cl_error =
153             clGetProgramInfo(program, CL_PROGRAM_BINARY_SIZES, sizeof(fileSize), &fileSize, nullptr);
154     if (cl_error != CL_SUCCESS)
155     {
156         GMX_THROW(InternalError("Could not get OpenCL program binary size, error was "
157                                 + ocl_get_error_string(cl_error)));
158     }
159
160     // TODO all this file writing stuff should become gmx::BinaryWriter
161     unsigned char* binary;
162     snew(binary, fileSize);
163     const unique_cptr<unsigned char> binaryGuard(binary);
164
165     cl_error = clGetProgramInfo(program, CL_PROGRAM_BINARIES, sizeof(binary), &binary, nullptr);
166     if (cl_error != CL_SUCCESS)
167     {
168         GMX_THROW(InternalError("Could not get OpenCL program binary, error was "
169                                 + ocl_get_error_string(cl_error)));
170     }
171
172     const auto f = create_unique_with_deleter(fopen(filename.c_str(), "wb"), fclose);
173     if (!f)
174     {
175         GMX_THROW(FileIOError("Failed to open binary cache file " + filename));
176     }
177
178     fwrite(binary, 1, fileSize, f.get());
179 }
180
181 } // namespace ocl
182 } // namespace gmx