xref: /libCEED/backends/cuda/ceed-cuda-compile.cpp (revision 672b0f2ac2d233f11bebf0085c50d29e53ac87eb)
1 // Copyright (c) 2017-2022, 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                 *jit_defs_path, *jit_defs_source, *ptx;
40   const int             num_opts = 3;
41   const char           *opts[num_opts];
42   nvrtcProgram          prog;
43   struct cudaDeviceProp prop;
44   Ceed_Cuda            *ceed_data;
45 
46   cudaFree(0);  // Make sure a Context exists for nvrtc
47 
48   std::ostringstream code;
49 
50   // Get kernel specific options, such as kernel constants
51   if (num_defines > 0) {
52     va_list args;
53     va_start(args, num_defines);
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     va_end(args);
63   }
64 
65   // Standard libCEED definitions for CUDA backends
66   CeedCallBackend(CeedGetJitAbsolutePath(ceed, "ceed/jit-source/cuda/cuda-jit.h", &jit_defs_path));
67   CeedCallBackend(CeedLoadSourceToBuffer(ceed, jit_defs_path, &jit_defs_source));
68   code << jit_defs_source;
69   code << "\n\n";
70   CeedCallBackend(CeedFree(&jit_defs_path));
71   CeedCallBackend(CeedFree(&jit_defs_source));
72 
73   // Non-macro options
74   opts[0] = "-default-device";
75   CeedCallBackend(CeedGetData(ceed, &ceed_data));
76   CeedCallCuda(ceed, cudaGetDeviceProperties(&prop, ceed_data->device_id));
77   std::string arch_arg = "-arch=compute_" + std::to_string(prop.major) + std::to_string(prop.minor);
78   opts[1]              = arch_arg.c_str();
79   opts[2]              = "-Dint32_t=int";
80 
81   // Add string source argument provided in call
82   code << source;
83 
84   // Create Program
85   CeedCallNvrtc(ceed, nvrtcCreateProgram(&prog, code.str().c_str(), NULL, 0, NULL, NULL));
86 
87   // Compile kernel
88   nvrtcResult result = nvrtcCompileProgram(prog, num_opts, opts);
89 
90   if (result != NVRTC_SUCCESS) {
91     char  *log;
92     size_t log_size;
93 
94     CeedCallNvrtc(ceed, nvrtcGetProgramLogSize(prog, &log_size));
95     CeedCallBackend(CeedMalloc(log_size, &log));
96     CeedCallNvrtc(ceed, nvrtcGetProgramLog(prog, log));
97     return CeedError(ceed, CEED_ERROR_BACKEND, "%s\n%s", nvrtcGetErrorString(result), log);
98   }
99 
100   CeedCallNvrtc(ceed, nvrtcGetPTXSize(prog, &ptx_size));
101   CeedCallBackend(CeedMalloc(ptx_size, &ptx));
102   CeedCallNvrtc(ceed, nvrtcGetPTX(prog, ptx));
103   CeedCallNvrtc(ceed, nvrtcDestroyProgram(&prog));
104 
105   CeedCallCuda(ceed, cuModuleLoadData(module, ptx));
106   CeedCallBackend(CeedFree(&ptx));
107   return CEED_ERROR_SUCCESS;
108 }
109 
110 //------------------------------------------------------------------------------
111 // Get CUDA kernel
112 //------------------------------------------------------------------------------
113 int CeedGetKernel_Cuda(Ceed ceed, CUmodule module, const char *name, CUfunction *kernel) {
114   CeedCallCuda(ceed, cuModuleGetFunction(kernel, module, name));
115   return CEED_ERROR_SUCCESS;
116 }
117 
118 //------------------------------------------------------------------------------
119 // Run CUDA kernel with block size selected automatically based on the kernel
120 //     (which may use enough registers to require a smaller block size than the
121 //      hardware is capable)
122 //------------------------------------------------------------------------------
123 int CeedRunKernelAutoblockCuda(Ceed ceed, CUfunction kernel, size_t points, void **args) {
124   int min_grid_size, max_block_size;
125 
126   CeedCallCuda(ceed, cuOccupancyMaxPotentialBlockSize(&min_grid_size, &max_block_size, kernel, NULL, 0, 0x10000));
127   CeedCallBackend(CeedRunKernel_Cuda(ceed, kernel, CeedDivUpInt(points, max_block_size), max_block_size, args));
128   return CEED_ERROR_SUCCESS;
129 }
130 
131 //------------------------------------------------------------------------------
132 // Run CUDA kernel
133 //------------------------------------------------------------------------------
134 int CeedRunKernel_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size, void **args) {
135   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, grid_size, block_size, 1, 1, 0, args));
136   return CEED_ERROR_SUCCESS;
137 }
138 
139 //------------------------------------------------------------------------------
140 // Run CUDA kernel for spatial dimension
141 //------------------------------------------------------------------------------
142 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,
143                           void **args) {
144   CeedCallBackend(CeedRunKernelDimShared_Cuda(ceed, kernel, grid_size, block_size_x, block_size_y, block_size_z, 0, args));
145   return CEED_ERROR_SUCCESS;
146 }
147 
148 //------------------------------------------------------------------------------
149 // Run CUDA kernel for spatial dimension with shared memory
150 //------------------------------------------------------------------------------
151 int CeedRunKernelDimShared_Cuda(Ceed ceed, CUfunction kernel, const int grid_size, const int block_size_x, const int block_size_y,
152                                 const int block_size_z, const int shared_mem_size, void **args) {
153 #if CUDA_VERSION >= 9000
154   cuFuncSetAttribute(kernel, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_mem_size);
155 #endif
156   CUresult result = cuLaunchKernel(kernel, grid_size, 1, 1, block_size_x, block_size_y, block_size_z, shared_mem_size, NULL, args, NULL);
157 
158   if (result == CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES) {
159     int max_threads_per_block, shared_size_bytes, num_regs;
160 
161     cuFuncGetAttribute(&max_threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, kernel);
162     cuFuncGetAttribute(&shared_size_bytes, CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES, kernel);
163     cuFuncGetAttribute(&num_regs, CU_FUNC_ATTRIBUTE_NUM_REGS, kernel);
164     return CeedError(ceed, CEED_ERROR_BACKEND,
165                      "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: max_threads_per_block %d on block size (%d,%d,%d), shared_size %d, num_regs %d",
166                      max_threads_per_block, block_size_x, block_size_y, block_size_z, shared_size_bytes, num_regs);
167   } else CeedChk_Cu(ceed, result);
168   return CEED_ERROR_SUCCESS;
169 }
170 
171 //------------------------------------------------------------------------------
172