xref: /libCEED/backends/cuda/ceed-cuda-compile.cpp (revision 7b3ff0698626cc2e5ce463afc10290072fd55c90)
1 // Copyright (c) 2017-2025, 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     CeedCallNvrtc(ceed, nvrtcGetProgramLogSize(prog, &log_size));
140     CeedCallBackend(CeedMalloc(log_size, &log));
141     CeedCallNvrtc(ceed, nvrtcGetProgramLog(prog, log));
142     if (throw_error) {
143       return CeedError(ceed, CEED_ERROR_BACKEND, "%s\n%s", nvrtcGetErrorString(result), log);
144     } else {
145       CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- COMPILE ERROR DETECTED ----------\n");
146       CeedDebug(ceed, "Error: %s\nCompile log:\n%s\n", nvrtcGetErrorString(result), log);
147       CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- BACKEND MAY FALLBACK ----------\n");
148       CeedCallBackend(CeedFree(&log));
149       CeedCallNvrtc(ceed, nvrtcDestroyProgram(&prog));
150       return CEED_ERROR_SUCCESS;
151     }
152   }
153 
154 #if CUDA_VERSION >= 11010
155   CeedCallNvrtc(ceed, nvrtcGetCUBINSize(prog, &ptx_size));
156   CeedCallBackend(CeedMalloc(ptx_size, &ptx));
157   CeedCallNvrtc(ceed, nvrtcGetCUBIN(prog, ptx));
158 #else
159   CeedCallNvrtc(ceed, nvrtcGetPTXSize(prog, &ptx_size));
160   CeedCallBackend(CeedMalloc(ptx_size, &ptx));
161   CeedCallNvrtc(ceed, nvrtcGetPTX(prog, ptx));
162 #endif
163   CeedCallNvrtc(ceed, nvrtcDestroyProgram(&prog));
164 
165   CeedCallCuda(ceed, cuModuleLoadData(module, ptx));
166   CeedCallBackend(CeedFree(&ptx));
167   return CEED_ERROR_SUCCESS;
168 }
169 
170 int CeedCompile_Cuda(Ceed ceed, const char *source, CUmodule *module, const CeedInt num_defines, ...) {
171   bool    is_compile_good = true;
172   va_list args;
173 
174   va_start(args, num_defines);
175   const CeedInt ierr = CeedCompileCore_Cuda(ceed, source, true, &is_compile_good, module, num_defines, args);
176 
177   va_end(args);
178   CeedCallBackend(ierr);
179   return CEED_ERROR_SUCCESS;
180 }
181 
182 int CeedTryCompile_Cuda(Ceed ceed, const char *source, bool *is_compile_good, CUmodule *module, const CeedInt num_defines, ...) {
183   va_list args;
184 
185   va_start(args, num_defines);
186   const CeedInt ierr = CeedCompileCore_Cuda(ceed, source, false, is_compile_good, module, num_defines, args);
187 
188   va_end(args);
189   CeedCallBackend(ierr);
190   return CEED_ERROR_SUCCESS;
191 }
192 
193 //------------------------------------------------------------------------------
194 // Get CUDA kernel
195 //------------------------------------------------------------------------------
196 int CeedGetKernel_Cuda(Ceed ceed, CUmodule module, const char *name, CUfunction *kernel) {
197   CeedCallCuda(ceed, cuModuleGetFunction(kernel, module, name));
198   return CEED_ERROR_SUCCESS;
199 }
200 
201 //------------------------------------------------------------------------------
202 // Run CUDA kernel with block size selected automatically based on the kernel
203 //     (which may use enough registers to require a smaller block size than the
204 //      hardware is capable)
205 //------------------------------------------------------------------------------
206 int CeedRunKernelAutoblockCuda(Ceed ceed, CUfunction kernel, size_t points, void **args) {
207   int min_grid_size, max_block_size;
208 
209   CeedCallCuda(ceed, cuOccupancyMaxPotentialBlockSize(&min_grid_size, &max_block_size, kernel, NULL, 0, 0x10000));
210   CeedCallBackend(CeedRunKernel_Cuda(ceed, kernel, CeedDivUpInt(points, max_block_size), max_block_size, args));
211   return CEED_ERROR_SUCCESS;
212 }
213 
214 //------------------------------------------------------------------------------
215 // Run CUDA kernel
216 //------------------------------------------------------------------------------
217 int CeedRunKernel_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size, void **args) {
218   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, NULL, grid_size, block_size, 1, 1, 0, args));
219   return CEED_ERROR_SUCCESS;
220 }
221 
222 //------------------------------------------------------------------------------
223 // Run CUDA kernel for spatial dimension
224 //------------------------------------------------------------------------------
225 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,
226                           void **args) {
227   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, NULL, grid_size, block_size_x, block_size_y, block_size_z, 0, args));
228   return CEED_ERROR_SUCCESS;
229 }
230 
231 //------------------------------------------------------------------------------
232 // Run CUDA kernel for spatial dimension with shared memory
233 //------------------------------------------------------------------------------
234 static int CeedRunKernelDimSharedCore_Cuda(Ceed ceed, CUfunction kernel, CUstream stream, const int grid_size, const int block_size_x,
235                                            const int block_size_y, const int block_size_z, const int shared_mem_size, const bool throw_error,
236                                            bool *is_good_run, void **args) {
237 #if CUDA_VERSION >= 9000
238   cuFuncSetAttribute(kernel, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_mem_size);
239 #endif
240   CUresult result = cuLaunchKernel(kernel, grid_size, 1, 1, block_size_x, block_size_y, block_size_z, shared_mem_size, stream, args, NULL);
241 
242   if (result == CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES) {
243     *is_good_run = false;
244     if (throw_error) {
245       int max_threads_per_block, shared_size_bytes, num_regs;
246 
247       cuFuncGetAttribute(&max_threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, kernel);
248       cuFuncGetAttribute(&shared_size_bytes, CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES, kernel);
249       cuFuncGetAttribute(&num_regs, CU_FUNC_ATTRIBUTE_NUM_REGS, kernel);
250       return CeedError(ceed, CEED_ERROR_BACKEND,
251                        "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: max_threads_per_block %d on block size (%d,%d,%d), shared_size %d, num_regs %d",
252                        max_threads_per_block, block_size_x, block_size_y, block_size_z, shared_size_bytes, num_regs);
253     }
254   } else CeedChk_Cu(ceed, result);
255   return CEED_ERROR_SUCCESS;
256 }
257 
258 int CeedRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, CUstream stream, const int grid_size, const int block_size_x, const int block_size_y,
259                                 const int block_size_z, const int shared_mem_size, void **args) {
260   bool is_good_run = true;
261 
262   CeedCallBackend(CeedRunKernelDimSharedCore_Cuda(ceed, kernel, stream, grid_size, block_size_x, block_size_y, block_size_z, shared_mem_size, true,
263                                                   &is_good_run, args));
264   return CEED_ERROR_SUCCESS;
265 }
266 
267 int CeedTryRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, CUstream stream, const int grid_size, const int block_size_x, const int block_size_y,
268                                    const int block_size_z, const int shared_mem_size, bool *is_good_run, void **args) {
269   CeedCallBackend(CeedRunKernelDimSharedCore_Cuda(ceed, kernel, stream, grid_size, block_size_x, block_size_y, block_size_z, shared_mem_size, false,
270                                                   is_good_run, args));
271   return CEED_ERROR_SUCCESS;
272 }
273 
274 //------------------------------------------------------------------------------
275