Project
Loading...
Searching...
No Matches
GPUReconstructionCUDAGenRTC.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
14
15#define GPUCA_GPUCODE_HOSTONLY
16
18#include "GPUParamRTC.h"
19#include "GPUDefParametersLoad.inc"
20#include <unistd.h>
21#include "Framework/SHA1.h"
22#include <sys/stat.h>
23#include <fcntl.h>
24#include <filesystem>
25
26#include <oneapi/tbb.h>
27using namespace o2::gpu;
28
30QGET_LD_BINARY_SYMBOLS(GPUReconstructionCUDArtc_src);
31QGET_LD_BINARY_SYMBOLS(GPUReconstructionCUDArtc_command);
32QGET_LD_BINARY_SYMBOLS(GPUReconstructionCUDArtc_command_arch);
33QGET_LD_BINARY_SYMBOLS(GPUReconstructionCUDArtc_command_no_fast_math);
34
35#include "GPUNoFastMathKernels.h"
36
37int32_t GPUReconstructionCUDA::genRTC(std::string& filename, uint32_t& nCompile)
38{
39 std::string rtcparam = std::string("#define GPUCA_RTC_CODE\n") +
40 std::string(GetProcessingSettings().rtc.optSpecialCode ? "#define GPUCA_RTC_SPECIAL_CODE(...) __VA_ARGS__\n" : "#define GPUCA_RTC_SPECIAL_CODE(...)\n") +
41 std::string(GetProcessingSettings().rtc.optConstexpr ? "#define GPUCA_RTC_CONSTEXPR constexpr\n" : "#define GPUCA_RTC_CONSTEXPR\n") +
42 GPUParamRTC::generateRTCCode(param(), GetProcessingSettings().rtc.optConstexpr);
43 if (filename == "") {
44 filename = "/tmp/o2cagpu_rtc_";
45 }
46 filename += std::to_string(getpid());
47 filename += "_";
48 filename += std::to_string(rand());
49
50 std::vector<std::string> kernels;
51 getRTCKernelCalls(kernels);
52 std::string kernelsall;
53 for (uint32_t i = 0; i < kernels.size(); i++) {
54 kernelsall += kernels[i] + "\n";
55 }
56
57 std::string baseCommand = (GetProcessingSettings().rtctech.prependCommand != "" ? (GetProcessingSettings().rtctech.prependCommand + " ") : "");
58 baseCommand += (getenv("O2_GPU_RTC_OVERRIDE_CMD") ? std::string(getenv("O2_GPU_RTC_OVERRIDE_CMD")) : std::string(_binary_GPUReconstructionCUDArtc_command_start, _binary_GPUReconstructionCUDArtc_command_len));
59 baseCommand += std::string(" ") + (GetProcessingSettings().rtctech.overrideArchitecture != "" ? GetProcessingSettings().rtctech.overrideArchitecture : std::string(_binary_GPUReconstructionCUDArtc_command_arch_start, _binary_GPUReconstructionCUDArtc_command_arch_len));
60
61 if (GetProcessingSettings().rtctech.loadLaunchBoundsFromFile.size()) {
62 FILE* fp = fopen(GetProcessingSettings().rtctech.loadLaunchBoundsFromFile.c_str(), "rb");
63 if (fp == nullptr) {
64 throw std::runtime_error("Cannot open launch bounds parameter module file");
65 }
66 fseek(fp, 0, SEEK_END);
67 size_t size = ftell(fp);
68 if (size != sizeof(*mParDevice)) {
69 throw std::runtime_error("launch bounds parameter file has incorrect size");
70 }
71 fseek(fp, 0, SEEK_SET);
72 if (fread(mParDevice, 1, size, fp) != size) {
73 throw std::runtime_error("Error reading launch bounds parameter file");
74 }
75 fclose(fp);
76 }
77 if constexpr (std::string_view("CUDA") == "HIP") { // Check if we are RTC-compiling for HIP
78 if (GetProcessingSettings().hipOverrideAMDEUSperCU > 0) {
79 mParDevice->par_AMD_EUS_PER_CU = GetProcessingSettings().hipOverrideAMDEUSperCU;
80 } else if (mParDevice->par_AMD_EUS_PER_CU <= 0) {
81 GPUFatal("AMD_EUS_PER_CU not set in the parameters provided for the AMD GPU, you can override this via --PROChipOverrideAMDEUSperCU [n]");
82 }
83 }
84 const std::string launchBounds = o2::gpu::internal::GPUDefParametersExport(*mParDevice, true, mParDevice->par_AMD_EUS_PER_CU ? (mParDevice->par_AMD_EUS_PER_CU * mWarpSize) : 0) +
85 "#define GPUCA_WARP_SIZE " + std::to_string(mWarpSize) + "\n";
86 if (GetProcessingSettings().rtctech.printLaunchBounds || GetProcessingSettings().debugLevel >= 3) {
87 GPUInfo("RTC Launch Bounds:\n%s", launchBounds.c_str());
88 }
89
90 const std::string compilerVersions = getBackendVersions();
91
92 char shasource[21], shaparam[21], shacmd[21], shakernels[21], shabounds[21], shaversion[21];
93 if (GetProcessingSettings().rtc.cacheOutput) {
94 o2::framework::internal::SHA1(shasource, _binary_GPUReconstructionCUDArtc_src_start, _binary_GPUReconstructionCUDArtc_src_len);
95 o2::framework::internal::SHA1(shaparam, rtcparam.c_str(), rtcparam.size());
96 o2::framework::internal::SHA1(shacmd, baseCommand.c_str(), baseCommand.size());
97 o2::framework::internal::SHA1(shakernels, kernelsall.c_str(), kernelsall.size());
98 o2::framework::internal::SHA1(shabounds, launchBounds.c_str(), launchBounds.size());
99 o2::framework::internal::SHA1(shaversion, compilerVersions.c_str(), compilerVersions.size());
100 }
101
102 nCompile = GetProcessingSettings().rtc.compilePerKernel ? kernels.size() : 1;
103 bool cacheLoaded = false;
104 int32_t fd = 0;
105 if (GetProcessingSettings().rtc.cacheOutput) {
106 if (GetProcessingSettings().rtctech.cacheFolder != ".") {
107 std::filesystem::create_directories(GetProcessingSettings().rtctech.cacheFolder);
108 }
109 if (GetProcessingSettings().rtctech.cacheMutex) {
110 mode_t mask = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
111 fd = open((GetProcessingSettings().rtctech.cacheFolder + "/cache.lock").c_str(), O_RDWR | O_CREAT | O_CLOEXEC, mask);
112 if (fd == -1) {
113 throw std::runtime_error("Error opening rtc cache mutex lock file");
114 }
115 fchmod(fd, mask);
116 if (lockf(fd, F_LOCK, 0)) {
117 throw std::runtime_error("Error locking rtc cache mutex file");
118 }
119 }
120
121 FILE* fp = fopen((GetProcessingSettings().rtctech.cacheFolder + "/rtc.cuda.cache").c_str(), "rb");
122 char sharead[20];
123 if (fp) {
124 size_t len;
125 while (true) {
126 auto checkSHA = [&](const char* shacmp, const char* name) {
127 if (fread(sharead, 1, 20, fp) != 20) {
128 throw std::runtime_error("Cache file corrupt");
129 }
130 if (GetProcessingSettings().debugLevel >= 3) {
131 char shaprint1[41], shaprint2[41];
132 for (uint32_t i = 0; i < 20; i++) {
133 sprintf(shaprint1 + 2 * i, "%02X ", shacmp[i]);
134 sprintf(shaprint2 + 2 * i, "%02X ", sharead[i]);
135 }
136 GPUInfo("SHA for %s: expected %s, read %s", name, shaprint1, shaprint2);
137 }
138 if (!GetProcessingSettings().rtctech.ignoreCacheValid && memcmp(sharead, shacmp, 20)) {
139 GPUInfo("Cache file content outdated (%s)", name);
140 return 1;
141 }
142 return 0;
143 };
144 if (checkSHA(shasource, "source") ||
145 checkSHA(shaparam, "param") ||
146 checkSHA(shacmd, "command line") ||
147 checkSHA(shakernels, "kernel definitions") ||
148 checkSHA(shabounds, "launch bounds") ||
149 checkSHA(shaversion, "compiler versions")) {
150 break;
151 }
152 GPUSettingsProcessingRTC cachedSettings;
153 static_assert(std::is_trivially_copyable_v<GPUSettingsProcessingRTC> == true, "GPUSettingsProcessingRTC must be POD");
154 if (fread(&cachedSettings, sizeof(cachedSettings), 1, fp) != 1) {
155 throw std::runtime_error("Cache file corrupt");
156 }
157 if (!GetProcessingSettings().rtctech.ignoreCacheValid && !(cachedSettings == GetProcessingSettings().rtc)) {
158 GPUInfo("Cache file content outdated (rtc parameters)");
159 break;
160 }
161 std::vector<char> buffer;
162 for (uint32_t i = 0; i < nCompile; i++) {
163 if (fread(&len, sizeof(len), 1, fp) != 1) {
164 throw std::runtime_error("Cache file corrupt");
165 }
166 buffer.resize(len);
167 if (fread(buffer.data(), 1, len, fp) != len) {
168 throw std::runtime_error("Cache file corrupt");
169 }
170 FILE* fp2 = fopen((filename + "_" + std::to_string(i) + mRtcBinExtension).c_str(), "w+b");
171 if (fp2 == nullptr) {
172 throw std::runtime_error("Cannot open tmp file");
173 }
174 if (fwrite(buffer.data(), 1, len, fp2) != len) {
175 throw std::runtime_error("Error writing file");
176 }
177 fclose(fp2);
178 }
179 GPUInfo("Using RTC cache file");
180 cacheLoaded = true;
181 break;
182 };
183 fclose(fp);
184 }
185 }
186 if (!cacheLoaded) {
187 if (GetProcessingSettings().debugLevel >= 0) {
188 GPUInfo("Starting CUDA RTC Compilation");
189 }
190 HighResTimer rtcTimer;
191 rtcTimer.ResetStart();
192 tbb::parallel_for<uint32_t>(0, nCompile, [&](auto i) {
193 if (GetProcessingSettings().debugLevel >= 3) {
194 printf("Compiling %s\n", (filename + "_" + std::to_string(i) + mRtcSrcExtension).c_str());
195 }
196 FILE* fp = fopen((filename + "_" + std::to_string(i) + mRtcSrcExtension).c_str(), "w+b");
197 if (fp == nullptr) {
198 throw std::runtime_error("Error opening file");
199 }
200
201 std::string kernel = "extern \"C\" {";
202 kernel += GetProcessingSettings().rtc.compilePerKernel ? kernels[i] : kernelsall;
203 kernel += "}";
204
205 bool deterministic = GetProcessingSettings().rtc.deterministic || (GetProcessingSettings().rtc.compilePerKernel && o2::gpu::internal::noFastMathKernels.find(GetKernelName(i)) != o2::gpu::internal::noFastMathKernels.end());
206 const std::string deterministicStr = std::string(deterministic ? "#define GPUCA_DETERMINISTIC_CODE(det, indet) det\n" : "#define GPUCA_DETERMINISTIC_CODE(det, indet) indet\n");
207
208 if (fwrite(deterministicStr.c_str(), 1, deterministicStr.size(), fp) != deterministicStr.size() ||
209 fwrite(rtcparam.c_str(), 1, rtcparam.size(), fp) != rtcparam.size() ||
210 fwrite(launchBounds.c_str(), 1, launchBounds.size(), fp) != launchBounds.size() ||
211 fwrite(_binary_GPUReconstructionCUDArtc_src_start, 1, _binary_GPUReconstructionCUDArtc_src_len, fp) != _binary_GPUReconstructionCUDArtc_src_len ||
212 fwrite(kernel.c_str(), 1, kernel.size(), fp) != kernel.size()) {
213 throw std::runtime_error("Error writing file");
214 }
215 fclose(fp);
216 std::string command = baseCommand;
217 if (deterministic) {
218 command += std::string(" ") + std::string(_binary_GPUReconstructionCUDArtc_command_no_fast_math_start, _binary_GPUReconstructionCUDArtc_command_no_fast_math_len);
219 }
220 command += " -c " + filename + "_" + std::to_string(i) + mRtcSrcExtension + " -o " + filename + "_" + std::to_string(i) + mRtcBinExtension;
221 if (GetProcessingSettings().debugLevel < 0) {
222 command += " &> /dev/null";
223 } else if (GetProcessingSettings().debugLevel < 2) {
224 command += " > /dev/null";
225 }
226 if (GetProcessingSettings().debugLevel >= 3) {
227 printf("Running command %s\n", command.c_str());
228 }
229 if (system(command.c_str())) {
230 if (GetProcessingSettings().debugLevel >= 3) {
231 printf("Source code file: %s", filename.c_str());
232 }
233 throw std::runtime_error("Error during CUDA compilation");
234 } // clang-format off
235 }, tbb::simple_partitioner()); // clang-format on
236 if (GetProcessingSettings().debugLevel >= 0) {
237 GPUInfo("RTC Compilation finished (%f seconds)", rtcTimer.GetCurrentElapsedTime());
238 }
239 if (GetProcessingSettings().rtc.cacheOutput) {
240 FILE* fp = fopen((GetProcessingSettings().rtctech.cacheFolder + "/rtc.cuda.cache").c_str(), "w+b");
241 if (fp == nullptr) {
242 throw std::runtime_error("Cannot open cache file for writing");
243 }
244 GPUInfo("Storing RTC compilation result in cache file");
245
246 if (fwrite(shasource, 1, 20, fp) != 20 ||
247 fwrite(shaparam, 1, 20, fp) != 20 ||
248 fwrite(shacmd, 1, 20, fp) != 20 ||
249 fwrite(shakernels, 1, 20, fp) != 20 ||
250 fwrite(shabounds, 1, 20, fp) != 20 ||
251 fwrite(shaversion, 1, 20, fp) != 20 ||
252 fwrite(&GetProcessingSettings().rtc, sizeof(GetProcessingSettings().rtc), 1, fp) != 1) {
253 throw std::runtime_error("Error writing cache file");
254 }
255
256 std::vector<char> buffer;
257 for (uint32_t i = 0; i < nCompile; i++) {
258 FILE* fp2 = fopen((filename + "_" + std::to_string(i) + mRtcBinExtension).c_str(), "rb");
259 if (fp2 == nullptr) {
260 throw std::runtime_error("Cannot open cuda module file");
261 }
262 fseek(fp2, 0, SEEK_END);
263 size_t size = ftell(fp2);
264 buffer.resize(size);
265 fseek(fp2, 0, SEEK_SET);
266 if (fread(buffer.data(), 1, size, fp2) != size) {
267 throw std::runtime_error("Error reading cuda module file");
268 }
269 fclose(fp2);
270
271 if (fwrite(&size, sizeof(size), 1, fp) != 1 ||
272 fwrite(buffer.data(), 1, size, fp) != size) {
273 throw std::runtime_error("Error writing cache file");
274 }
275 }
276 fclose(fp);
277 }
278 }
279 if (GetProcessingSettings().rtc.cacheOutput && GetProcessingSettings().rtctech.cacheMutex) {
280 if (lockf(fd, F_ULOCK, 0)) {
281 throw std::runtime_error("Error unlocking RTC cache mutex file");
282 }
283 close(fd);
284 }
285
286 return 0;
287}
int32_t i
double GetCurrentElapsedTime(bool reset=false)
Definition timer.cxx:117
void ResetStart()
Definition timer.cxx:70
static const char * GetKernelName()
const GPUSettingsProcessing & GetProcessingSettings() const
GLsizei const GLchar *const * string
Definition glcorearb.h:809
GLuint buffer
Definition glcorearb.h:655
GLsizeiptr size
Definition glcorearb.h:659
GLuint const GLchar * name
Definition glcorearb.h:781
GLenum GLenum GLsizei len
Definition glcorearb.h:4232
GLenum GLfloat param
Definition glcorearb.h:271
GLint GLuint mask
Definition glcorearb.h:291
Polygon< T > close(Polygon< T > polygon)
Definition Polygon.h:126
Defining DataPointCompositeObject explicitly as copiable.
std::string to_string(gsl::span< T, Size > span)
Definition common.h:52
std::string filename()
#define QGET_LD_BINARY_SYMBOLS(filename)