xref: /libCEED/backends/cuda/ceed-cuda-compile.cpp (revision daaf13a462f999a7d367f3df68e0e3c34270722c)
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 int CeedCompile_Cuda(Ceed ceed, const char *source, CUmodule *module, const CeedInt num_defines, ...) {
38   size_t                ptx_size;
39   char                 *ptx;
40   const char           *jit_defs_path, *jit_defs_source;
41   const int             num_opts = 4;
42   const char           *opts[num_opts];
43   nvrtcProgram          prog;
44   struct cudaDeviceProp prop;
45   Ceed_Cuda            *ceed_data;
46 
47   cudaFree(0);  // Make sure a Context exists for nvrtc
48 
49   std::ostringstream code;
50 
51   // Get kernel specific options, such as kernel constants
52   if (num_defines > 0) {
53     va_list args;
54     va_start(args, num_defines);
55     char *name;
56     int   val;
57 
58     for (int i = 0; i < num_defines; i++) {
59       name = va_arg(args, char *);
60       val  = va_arg(args, int);
61       code << "#define " << name << " " << val << "\n";
62     }
63     va_end(args);
64   }
65 
66   // Standard libCEED definitions for CUDA backends
67   CeedCallBackend(CeedGetJitAbsolutePath(ceed, "ceed/jit-source/cuda/cuda-jit.h", &jit_defs_path));
68   {
69     char *source;
70 
71     CeedCallBackend(CeedLoadSourceToBuffer(ceed, jit_defs_path, &source));
72     jit_defs_source = source;
73   }
74   code << jit_defs_source;
75   code << "\n\n";
76   CeedCallBackend(CeedFree(&jit_defs_path));
77   CeedCallBackend(CeedFree(&jit_defs_source));
78 
79   // Non-macro options
80   opts[0] = "-default-device";
81   CeedCallBackend(CeedGetData(ceed, &ceed_data));
82   CeedCallCuda(ceed, cudaGetDeviceProperties(&prop, ceed_data->device_id));
83   std::string arch_arg =
84 #if CUDA_VERSION >= 11010
85       // NVRTC used to support only virtual architectures through the option
86       // -arch, since it was only emitting PTX. It will now support actual
87       // architectures as well to emit SASS.
88       // https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#dynamic-code-generation
89       "-arch=sm_"
90 #else
91       "-arch=compute_"
92 #endif
93       + std::to_string(prop.major) + std::to_string(prop.minor);
94   opts[1] = arch_arg.c_str();
95   opts[2] = "-Dint32_t=int";
96   opts[3] = "-I/home/jeremy/Dev/libCEED/include/ceed/jit-source/"
97 
98   // Add string source argument provided in call
99   code << source;
100 
101   // Create Program
102   CeedCallNvrtc(ceed, nvrtcCreateProgram(&prog, code.str().c_str(), NULL, 0, NULL, NULL));
103 
104   // Compile kernel
105   nvrtcResult result = nvrtcCompileProgram(prog, num_opts, opts);
106 
107   if (result != NVRTC_SUCCESS) {
108     char  *log;
109     size_t log_size;
110 
111     CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- CEED JIT SOURCE FAILED TO COMPILE ----------\n");
112     CeedDebug(ceed, "Source:\n%s\n", code.str().c_str());
113     CeedDebug256(ceed, CEED_DEBUG_COLOR_ERROR, "---------- CEED JIT SOURCE FAILED TO COMPILE ----------\n");
114     CeedCallNvrtc(ceed, nvrtcGetProgramLogSize(prog, &log_size));
115     CeedCallBackend(CeedMalloc(log_size, &log));
116     CeedCallNvrtc(ceed, nvrtcGetProgramLog(prog, log));
117     return CeedError(ceed, CEED_ERROR_BACKEND, "%s\n%s", nvrtcGetErrorString(result), log);
118   }
119 
120 #if CUDA_VERSION >= 11010
121   CeedCallNvrtc(ceed, nvrtcGetCUBINSize(prog, &ptx_size));
122   CeedCallBackend(CeedMalloc(ptx_size, &ptx));
123   CeedCallNvrtc(ceed, nvrtcGetCUBIN(prog, ptx));
124 #else
125   CeedCallNvrtc(ceed, nvrtcGetPTXSize(prog, &ptx_size));
126   CeedCallBackend(CeedMalloc(ptx_size, &ptx));
127   CeedCallNvrtc(ceed, nvrtcGetPTX(prog, ptx));
128 #endif
129   CeedCallNvrtc(ceed, nvrtcDestroyProgram(&prog));
130 
131   CeedCallCuda(ceed, cuModuleLoadData(module, ptx));
132   CeedCallBackend(CeedFree(&ptx));
133   return CEED_ERROR_SUCCESS;
134 }
135 
136 //------------------------------------------------------------------------------
137 // Get CUDA kernel
138 //------------------------------------------------------------------------------
139 int CeedGetKernel_Cuda(Ceed ceed, CUmodule module, const char *name, CUfunction *kernel) {
140   CeedCallCuda(ceed, cuModuleGetFunction(kernel, module, name));
141   return CEED_ERROR_SUCCESS;
142 }
143 
144 //------------------------------------------------------------------------------
145 // Run CUDA kernel with block size selected automatically based on the kernel
146 //     (which may use enough registers to require a smaller block size than the
147 //      hardware is capable)
148 //------------------------------------------------------------------------------
149 int CeedRunKernelAutoblockCuda(Ceed ceed, CUfunction kernel, size_t points, void **args) {
150   int min_grid_size, max_block_size;
151 
152   CeedCallCuda(ceed, cuOccupancyMaxPotentialBlockSize(&min_grid_size, &max_block_size, kernel, NULL, 0, 0x10000));
153   CeedCallBackend(CeedRunKernel_Cuda(ceed, kernel, CeedDivUpInt(points, max_block_size), max_block_size, args));
154   return CEED_ERROR_SUCCESS;
155 }
156 
157 //------------------------------------------------------------------------------
158 // Run CUDA kernel
159 //------------------------------------------------------------------------------
160 int CeedRunKernel_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size, void **args) {
161   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, grid_size, block_size, 1, 1, 0, args));
162   return CEED_ERROR_SUCCESS;
163 }
164 
165 //------------------------------------------------------------------------------
166 // Run CUDA kernel for spatial dimension
167 //------------------------------------------------------------------------------
168 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,
169                           void **args) {
170   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, grid_size, block_size_x, block_size_y, block_size_z, 0, args));
171   return CEED_ERROR_SUCCESS;
172 }
173 
174 //------------------------------------------------------------------------------
175 // Run CUDA kernel for spatial dimension with shared memory
176 //------------------------------------------------------------------------------
177 int CeedRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size_x, const int block_size_y,
178                                 const int block_size_z, const int shared_mem_size, void **args) {
179 #if CUDA_VERSION >= 9000
180   cuFuncSetAttribute(kernel, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_mem_size);
181 #endif
182   CUresult result = cuLaunchKernel(kernel, grid_size, 1, 1, block_size_x, block_size_y, block_size_z, shared_mem_size, NULL, args, NULL);
183 
184   if (result == CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES) {
185     int max_threads_per_block, shared_size_bytes, num_regs;
186 
187     cuFuncGetAttribute(&max_threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, kernel);
188     cuFuncGetAttribute(&shared_size_bytes, CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES, kernel);
189     cuFuncGetAttribute(&num_regs, CU_FUNC_ATTRIBUTE_NUM_REGS, kernel);
190     return CeedError(ceed, CEED_ERROR_BACKEND,
191                      "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: max_threads_per_block %d on block size (%d,%d,%d), shared_size %d, num_regs %d",
192                      max_threads_per_block, block_size_x, block_size_y, block_size_z, shared_size_bytes, num_regs);
193   } else CeedChk_Cu(ceed, result);
194   return CEED_ERROR_SUCCESS;
195 }
196 
197 //------------------------------------------------------------------------------
198