xref: /libCEED/backends/cuda/ceed-cuda-compile.cpp (revision ddae5012d4ca987da08499b586cefc9e622c3919)
1 // Copyright (c) 2017-2024, Lawrence Livermore National Security, LLC and other CEED contributors.
2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3 //
4 // SPDX-License-Identifier: BSD-2-Clause
5 //
6 // This file is part of CEED:  http://github.com/ceed
7 
8 #include "ceed-cuda-compile.h"
9 
10 #include <ceed.h>
11 #include <ceed/backend.h>
12 #include <ceed/jit-tools.h>
13 #include <cuda_runtime.h>
14 #include <nvrtc.h>
15 #include <stdarg.h>
16 #include <string.h>
17 
18 #include <sstream>
19 
20 #include "ceed-cuda-common.h"
21 
22 #define CeedChk_Nvrtc(ceed, x)                                                                              \
23   do {                                                                                                      \
24     nvrtcResult result = static_cast<nvrtcResult>(x);                                                       \
25     if (result != NVRTC_SUCCESS) return CeedError((ceed), CEED_ERROR_BACKEND, nvrtcGetErrorString(result)); \
26   } while (0)
27 
28 #define CeedCallNvrtc(ceed, ...)  \
29   do {                            \
30     int ierr_q_ = __VA_ARGS__;    \
31     CeedChk_Nvrtc(ceed, ierr_q_); \
32   } while (0)
33 
34 //------------------------------------------------------------------------------
35 // Compile CUDA kernel
36 //------------------------------------------------------------------------------
37 static int CeedCompileCore_Cuda(Ceed ceed, const char *source, const bool throw_error, bool *is_compile_good, CUmodule *module,
38                                 const CeedInt num_defines, va_list args) {
39   size_t                ptx_size;
40   char                 *ptx;
41   const int             num_opts            = 4;
42   CeedInt               num_jit_source_dirs = 0, num_jit_defines = 0;
43   const char          **opts;
44   nvrtcProgram          prog;
45   struct cudaDeviceProp prop;
46   Ceed_Cuda            *ceed_data;
47 
48   cudaFree(0);  // Make sure a Context exists for nvrtc
49 
50   std::ostringstream code;
51 
52   // Get kernel specific options, such as kernel constants
53   if (num_defines > 0) {
54     char *name;
55     int   val;
56 
57     for (int i = 0; i < num_defines; i++) {
58       name = va_arg(args, char *);
59       val  = va_arg(args, int);
60       code << "#define " << name << " " << val << "\n";
61     }
62   }
63 
64   // Standard libCEED definitions for CUDA backends
65   code << "#include <ceed/jit-source/cuda/cuda-jit.h>\n\n";
66 
67   // Non-macro options
68   CeedCallBackend(CeedCalloc(num_opts, &opts));
69   opts[0] = "-default-device";
70   CeedCallBackend(CeedGetData(ceed, &ceed_data));
71   CeedCallCuda(ceed, cudaGetDeviceProperties(&prop, ceed_data->device_id));
72   std::string arch_arg =
73 #if CUDA_VERSION >= 11010
74       // NVRTC used to support only virtual architectures through the option
75       // -arch, since it was only emitting PTX. It will now support actual
76       // architectures as well to emit SASS.
77       // https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#dynamic-code-generation
78       "-arch=sm_"
79 #else
80       "-arch=compute_"
81 #endif
82       + std::to_string(prop.major) + std::to_string(prop.minor);
83   opts[1] = arch_arg.c_str();
84   opts[2] = "-Dint32_t=int";
85   opts[3] = "-DCEED_RUNNING_JIT_PASS=1";
86   // Additional include dirs
87   {
88     const char **jit_source_dirs;
89 
90     CeedCallBackend(CeedGetJitSourceRoots(ceed, &num_jit_source_dirs, &jit_source_dirs));
91     CeedCallBackend(CeedRealloc(num_opts + num_jit_source_dirs, &opts));
92     for (CeedInt i = 0; i < num_jit_source_dirs; i++) {
93       std::ostringstream include_dir_arg;
94 
95       include_dir_arg << "-I" << jit_source_dirs[i];
96       CeedCallBackend(CeedStringAllocCopy(include_dir_arg.str().c_str(), (char **)&opts[num_opts + i]));
97     }
98     CeedCallBackend(CeedRestoreJitSourceRoots(ceed, &jit_source_dirs));
99   }
100   // User defines
101   {
102     const char **jit_defines;
103 
104     CeedCallBackend(CeedGetJitDefines(ceed, &num_jit_defines, &jit_defines));
105     CeedCallBackend(CeedRealloc(num_opts + num_jit_source_dirs + num_jit_defines, &opts));
106     for (CeedInt i = 0; i < num_jit_defines; i++) {
107       std::ostringstream define_arg;
108 
109       define_arg << "-D" << jit_defines[i];
110       CeedCallBackend(CeedStringAllocCopy(define_arg.str().c_str(), (char **)&opts[num_opts + num_jit_source_dirs + i]));
111     }
112     CeedCallBackend(CeedRestoreJitDefines(ceed, &jit_defines));
113   }
114 
115   // Add string source argument provided in call
116   code << source;
117 
118   // Create Program
119   CeedCallNvrtc(ceed, nvrtcCreateProgram(&prog, code.str().c_str(), NULL, 0, NULL, NULL));
120 
121   // Compile kernel
122   CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- ATTEMPTING TO COMPILE JIT SOURCE ----------\n");
123   CeedDebug(ceed, "Source:\n%s\n", code.str().c_str());
124   CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- END OF JIT SOURCE ----------\n");
125   nvrtcResult result = nvrtcCompileProgram(prog, num_opts + num_jit_source_dirs + num_jit_defines, opts);
126 
127   for (CeedInt i = 0; i < num_jit_source_dirs; i++) {
128     CeedCallBackend(CeedFree(&opts[num_opts + i]));
129   }
130   for (CeedInt i = 0; i < num_jit_defines; i++) {
131     CeedCallBackend(CeedFree(&opts[num_opts + num_jit_source_dirs + i]));
132   }
133   CeedCallBackend(CeedFree(&opts));
134   *is_compile_good = result == NVRTC_SUCCESS;
135   if (!*is_compile_good) {
136     char  *log;
137     size_t log_size;
138 
139     if (throw_error) {
140       CeedCallNvrtc(ceed, nvrtcGetProgramLogSize(prog, &log_size));
141       CeedCallBackend(CeedMalloc(log_size, &log));
142       CeedCallNvrtc(ceed, nvrtcGetProgramLog(prog, log));
143       return CeedError(ceed, CEED_ERROR_BACKEND, "%s\n%s", nvrtcGetErrorString(result), log);
144     }
145   }
146 
147 #if CUDA_VERSION >= 11010
148   CeedCallNvrtc(ceed, nvrtcGetCUBINSize(prog, &ptx_size));
149   CeedCallBackend(CeedMalloc(ptx_size, &ptx));
150   CeedCallNvrtc(ceed, nvrtcGetCUBIN(prog, ptx));
151 #else
152   CeedCallNvrtc(ceed, nvrtcGetPTXSize(prog, &ptx_size));
153   CeedCallBackend(CeedMalloc(ptx_size, &ptx));
154   CeedCallNvrtc(ceed, nvrtcGetPTX(prog, ptx));
155 #endif
156   CeedCallNvrtc(ceed, nvrtcDestroyProgram(&prog));
157 
158   CeedCallCuda(ceed, cuModuleLoadData(module, ptx));
159   CeedCallBackend(CeedFree(&ptx));
160   return CEED_ERROR_SUCCESS;
161 }
162 
163 int CeedCompile_Cuda(Ceed ceed, const char *source, CUmodule *module, const CeedInt num_defines, ...) {
164   bool    is_compile_good = true;
165   va_list args;
166 
167   va_start(args, num_defines);
168   CeedCallBackend(CeedCompileCore_Cuda(ceed, source, true, &is_compile_good, module, num_defines, args));
169   va_end(args);
170   return CEED_ERROR_SUCCESS;
171 }
172 
173 int CeedTryCompile_Cuda(Ceed ceed, const char *source, bool *is_compile_good, CUmodule *module, const CeedInt num_defines, ...) {
174   va_list args;
175 
176   va_start(args, num_defines);
177   CeedCallBackend(CeedCompileCore_Cuda(ceed, source, false, is_compile_good, module, num_defines, args));
178   va_end(args);
179   return CEED_ERROR_SUCCESS;
180 }
181 
182 //------------------------------------------------------------------------------
183 // Get CUDA kernel
184 //------------------------------------------------------------------------------
185 int CeedGetKernel_Cuda(Ceed ceed, CUmodule module, const char *name, CUfunction *kernel) {
186   CeedCallCuda(ceed, cuModuleGetFunction(kernel, module, name));
187   return CEED_ERROR_SUCCESS;
188 }
189 
190 //------------------------------------------------------------------------------
191 // Run CUDA kernel with block size selected automatically based on the kernel
192 //     (which may use enough registers to require a smaller block size than the
193 //      hardware is capable)
194 //------------------------------------------------------------------------------
195 int CeedRunKernelAutoblockCuda(Ceed ceed, CUfunction kernel, size_t points, void **args) {
196   int min_grid_size, max_block_size;
197 
198   CeedCallCuda(ceed, cuOccupancyMaxPotentialBlockSize(&min_grid_size, &max_block_size, kernel, NULL, 0, 0x10000));
199   CeedCallBackend(CeedRunKernel_Cuda(ceed, kernel, CeedDivUpInt(points, max_block_size), max_block_size, args));
200   return CEED_ERROR_SUCCESS;
201 }
202 
203 //------------------------------------------------------------------------------
204 // Run CUDA kernel
205 //------------------------------------------------------------------------------
206 int CeedRunKernel_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size, void **args) {
207   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, grid_size, block_size, 1, 1, 0, args));
208   return CEED_ERROR_SUCCESS;
209 }
210 
211 //------------------------------------------------------------------------------
212 // Run CUDA kernel for spatial dimension
213 //------------------------------------------------------------------------------
214 int CeedRunKernelDim_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size_x, const int block_size_y, const int block_size_z,
215                           void **args) {
216   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, grid_size, block_size_x, block_size_y, block_size_z, 0, args));
217   return CEED_ERROR_SUCCESS;
218 }
219 
220 //------------------------------------------------------------------------------
221 // Run CUDA kernel for spatial dimension with shared memory
222 //------------------------------------------------------------------------------
223 static int CeedRunKernelDimSharedCore_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size_x, const int block_size_y,
224                                            const int block_size_z, const int shared_mem_size, const bool throw_error, bool *is_good_run,
225                                            void **args) {
226 #if CUDA_VERSION >= 9000
227   cuFuncSetAttribute(kernel, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_mem_size);
228 #endif
229   CUresult result = cuLaunchKernel(kernel, grid_size, 1, 1, block_size_x, block_size_y, block_size_z, shared_mem_size, NULL, args, NULL);
230 
231   if (result == CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES) {
232     *is_good_run = false;
233     if (throw_error) {
234       int max_threads_per_block, shared_size_bytes, num_regs;
235 
236       cuFuncGetAttribute(&max_threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, kernel);
237       cuFuncGetAttribute(&shared_size_bytes, CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES, kernel);
238       cuFuncGetAttribute(&num_regs, CU_FUNC_ATTRIBUTE_NUM_REGS, kernel);
239       return CeedError(ceed, CEED_ERROR_BACKEND,
240                        "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: max_threads_per_block %d on block size (%d,%d,%d), shared_size %d, num_regs %d",
241                        max_threads_per_block, block_size_x, block_size_y, block_size_z, shared_size_bytes, num_regs);
242     }
243   } else CeedChk_Cu(ceed, result);
244   return CEED_ERROR_SUCCESS;
245 }
246 
247 int CeedRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size_x, const int block_size_y,
248                                 const int block_size_z, const int shared_mem_size, void **args) {
249   bool is_good_run = true;
250 
251   CeedCallBackend(
252       CeedRunKernelDimSharedCore_Cuda(ceed, kernel, grid_size, block_size_x, block_size_y, block_size_z, shared_mem_size, true, &is_good_run, args));
253   return CEED_ERROR_SUCCESS;
254 }
255 
256 int CeedTryRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size_x, const int block_size_y,
257                                    const int block_size_z, const int shared_mem_size, bool *is_good_run, void **args) {
258   CeedCallBackend(
259       CeedRunKernelDimSharedCore_Cuda(ceed, kernel, grid_size, block_size_x, block_size_y, block_size_z, shared_mem_size, false, is_good_run, args));
260   return CEED_ERROR_SUCCESS;
261 }
262 
263 //------------------------------------------------------------------------------
264