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.h> 9 #include <ceed/backend.h> 10 #include <ceed/jit-source/cuda/cuda-types.h> 11 #include <cuda.h> 12 #include <cuda_runtime.h> 13 #include <stddef.h> 14 #include <string.h> 15 16 #include "../cuda/ceed-cuda-common.h" 17 #include "../cuda/ceed-cuda-compile.h" 18 #include "ceed-cuda-gen-operator-build.h" 19 #include "ceed-cuda-gen.h" 20 21 //------------------------------------------------------------------------------ 22 // Destroy operator 23 //------------------------------------------------------------------------------ 24 static int CeedOperatorDestroy_Cuda_gen(CeedOperator op) { 25 Ceed ceed; 26 CeedOperator_Cuda_gen *impl; 27 28 CeedCallBackend(CeedOperatorGetCeed(op, &ceed)); 29 CeedCallBackend(CeedOperatorGetData(op, &impl)); 30 if (impl->points.num_per_elem) CeedCallCuda(ceed, cudaFree((void **)impl->points.num_per_elem)); 31 CeedCallBackend(CeedFree(&impl)); 32 CeedCallBackend(CeedDestroy(&ceed)); 33 return CEED_ERROR_SUCCESS; 34 } 35 36 static int Waste(int threads_per_sm, int warp_size, int threads_per_elem, int elems_per_block) { 37 int useful_threads_per_block = threads_per_elem * elems_per_block; 38 // round up to nearest multiple of warp_size 39 int block_size = CeedDivUpInt(useful_threads_per_block, warp_size) * warp_size; 40 int blocks_per_sm = threads_per_sm / block_size; 41 return threads_per_sm - useful_threads_per_block * blocks_per_sm; 42 } 43 44 // Choose the least wasteful block size constrained by blocks_per_sm of max_threads_per_block. 45 // 46 // The x and y part of block[] contains per-element sizes (specified on input) while the z part is number of elements. 47 // 48 // Problem setting: we'd like to make occupancy high with relatively few inactive threads. CUDA (cuOccupancyMaxPotentialBlockSize) can tell us how 49 // many threads can run. 50 // 51 // Note that full occupancy sometimes can't be achieved by one thread block. 52 // For example, an SM might support 1536 threads in total, but only 1024 within a single thread block. 53 // So cuOccupancyMaxPotentialBlockSize may suggest a block size of 768 so that two blocks can run, versus one block of 1024 will prevent a second 54 // block from running. The cuda-gen kernels are pretty heavy with lots of instruction-level parallelism (ILP) so we'll generally be okay with 55 // relatively low occupancy and smaller thread blocks, but we solve a reasonably general problem here. Empirically, we find that blocks bigger than 56 // about 256 have higher latency and worse load balancing when the number of elements is modest. 57 // 58 // cuda-gen can't choose block sizes arbitrarily; they need to be a multiple of the number of quadrature points (or number of basis functions). 59 // They also have a lot of __syncthreads(), which is another point against excessively large thread blocks. 60 // Suppose I have elements with 7x7x7 quadrature points. 61 // This will loop over the last dimension, so we have 7*7=49 threads per element. 62 // Suppose we have two elements = 2*49=98 useful threads. 63 // CUDA schedules in units of full warps (32 threads), so 128 CUDA hardware threads are effectively committed to that block. 64 // Now suppose cuOccupancyMaxPotentialBlockSize returned 352. 65 // We can schedule 2 blocks of size 98 (196 useful threads using 256 hardware threads), but not a third block (which would need a total of 384 66 // hardware threads). 67 // 68 // If instead, we had packed 3 elements, we'd have 3*49=147 useful threads occupying 160 slots, and could schedule two blocks. 69 // Alternatively, we could pack a single block of 7 elements (2*49=343 useful threads) into the 354 slots. 70 // The latter has the least "waste", but __syncthreads() over-synchronizes and it might not pay off relative to smaller blocks. 71 static int BlockGridCalculate(CeedInt num_elem, int blocks_per_sm, int max_threads_per_block, int max_threads_z, int warp_size, int block[3], 72 int *grid) { 73 const int threads_per_sm = blocks_per_sm * max_threads_per_block; 74 const int threads_per_elem = block[0] * block[1]; 75 int elems_per_block = 1; 76 int waste = Waste(threads_per_sm, warp_size, threads_per_elem, 1); 77 78 for (int i = 2; i <= CeedIntMin(max_threads_per_block / threads_per_elem, num_elem); i++) { 79 int i_waste = Waste(threads_per_sm, warp_size, threads_per_elem, i); 80 81 // We want to minimize waste, but smaller kernels have lower latency and less __syncthreads() overhead so when a larger block size has the same 82 // waste as a smaller one, go ahead and prefer the smaller block. 83 if (i_waste < waste || (i_waste == waste && threads_per_elem * i <= 128)) { 84 elems_per_block = i; 85 waste = i_waste; 86 } 87 } 88 // In low-order elements, threads_per_elem may be sufficiently low to give an elems_per_block greater than allowable for the device, so we must 89 // check before setting the z-dimension size of the block. 90 block[2] = CeedIntMin(elems_per_block, max_threads_z); 91 *grid = CeedDivUpInt(num_elem, elems_per_block); 92 return CEED_ERROR_SUCCESS; 93 } 94 95 // callback for cuOccupancyMaxPotentialBlockSize, providing the amount of dynamic shared memory required for a thread block of size threads. 96 static size_t dynamicSMemSize(int threads) { return threads * sizeof(CeedScalar); } 97 98 //------------------------------------------------------------------------------ 99 // Apply and add to output 100 //------------------------------------------------------------------------------ 101 static int CeedOperatorApplyAddCore_Cuda_gen(CeedOperator op, CUstream stream, const CeedScalar *input_arr, CeedScalar *output_arr, bool *is_run_good, 102 CeedRequest *request) { 103 bool is_at_points, is_tensor; 104 Ceed ceed; 105 Ceed_Cuda *cuda_data; 106 CeedInt num_elem, num_input_fields, num_output_fields; 107 CeedEvalMode eval_mode; 108 CeedQFunctionField *qf_input_fields, *qf_output_fields; 109 CeedQFunction_Cuda_gen *qf_data; 110 CeedQFunction qf; 111 CeedOperatorField *op_input_fields, *op_output_fields; 112 CeedOperator_Cuda_gen *data; 113 114 // Build the operator kernel 115 CeedCallBackend(CeedOperatorBuildKernel_Cuda_gen(op, is_run_good)); 116 if (!(*is_run_good)) return CEED_ERROR_SUCCESS; 117 118 CeedCallBackend(CeedOperatorGetCeed(op, &ceed)); 119 CeedCallBackend(CeedGetData(ceed, &cuda_data)); 120 CeedCallBackend(CeedOperatorGetData(op, &data)); 121 CeedCallBackend(CeedOperatorGetQFunction(op, &qf)); 122 CeedCallBackend(CeedQFunctionGetData(qf, &qf_data)); 123 CeedCallBackend(CeedOperatorGetNumElements(op, &num_elem)); 124 CeedCallBackend(CeedOperatorGetFields(op, &num_input_fields, &op_input_fields, &num_output_fields, &op_output_fields)); 125 CeedCallBackend(CeedQFunctionGetFields(qf, NULL, &qf_input_fields, NULL, &qf_output_fields)); 126 127 // Input vectors 128 for (CeedInt i = 0; i < num_input_fields; i++) { 129 CeedCallBackend(CeedQFunctionFieldGetEvalMode(qf_input_fields[i], &eval_mode)); 130 if (eval_mode == CEED_EVAL_WEIGHT) { // Skip 131 data->fields.inputs[i] = NULL; 132 } else { 133 bool is_active; 134 CeedVector vec; 135 136 // Get input vector 137 CeedCallBackend(CeedOperatorFieldGetVector(op_input_fields[i], &vec)); 138 is_active = vec == CEED_VECTOR_ACTIVE; 139 if (is_active) data->fields.inputs[i] = input_arr; 140 else CeedCallBackend(CeedVectorGetArrayRead(vec, CEED_MEM_DEVICE, &data->fields.inputs[i])); 141 CeedCallBackend(CeedVectorDestroy(&vec)); 142 } 143 } 144 145 // Output vectors 146 for (CeedInt i = 0; i < num_output_fields; i++) { 147 CeedCallBackend(CeedQFunctionFieldGetEvalMode(qf_output_fields[i], &eval_mode)); 148 if (eval_mode == CEED_EVAL_WEIGHT) { // Skip 149 data->fields.outputs[i] = NULL; 150 } else { 151 bool is_active; 152 CeedVector vec; 153 154 // Get output vector 155 CeedCallBackend(CeedOperatorFieldGetVector(op_output_fields[i], &vec)); 156 is_active = vec == CEED_VECTOR_ACTIVE; 157 if (is_active) data->fields.outputs[i] = output_arr; 158 else CeedCallBackend(CeedVectorGetArray(vec, CEED_MEM_DEVICE, &data->fields.outputs[i])); 159 CeedCallBackend(CeedVectorDestroy(&vec)); 160 } 161 } 162 163 // Point coordinates, if needed 164 CeedCallBackend(CeedOperatorIsAtPoints(op, &is_at_points)); 165 if (is_at_points) { 166 // Coords 167 CeedVector vec; 168 169 CeedCallBackend(CeedOperatorAtPointsGetPoints(op, NULL, &vec)); 170 CeedCallBackend(CeedVectorGetArrayRead(vec, CEED_MEM_DEVICE, &data->points.coords)); 171 CeedCallBackend(CeedVectorDestroy(&vec)); 172 173 // Points per elem 174 if (num_elem != data->points.num_elem) { 175 CeedInt *points_per_elem; 176 const CeedInt num_bytes = num_elem * sizeof(CeedInt); 177 CeedElemRestriction rstr_points = NULL; 178 179 data->points.num_elem = num_elem; 180 CeedCallBackend(CeedOperatorAtPointsGetPoints(op, &rstr_points, NULL)); 181 CeedCallBackend(CeedCalloc(num_elem, &points_per_elem)); 182 for (CeedInt e = 0; e < num_elem; e++) { 183 CeedInt num_points_elem; 184 185 CeedCallBackend(CeedElemRestrictionGetNumPointsInElement(rstr_points, e, &num_points_elem)); 186 points_per_elem[e] = num_points_elem; 187 } 188 if (data->points.num_per_elem) CeedCallCuda(ceed, cudaFree((void **)data->points.num_per_elem)); 189 CeedCallCuda(ceed, cudaMalloc((void **)&data->points.num_per_elem, num_bytes)); 190 CeedCallCuda(ceed, cudaMemcpy((void *)data->points.num_per_elem, points_per_elem, num_bytes, cudaMemcpyHostToDevice)); 191 CeedCallBackend(CeedElemRestrictionDestroy(&rstr_points)); 192 CeedCallBackend(CeedFree(&points_per_elem)); 193 } 194 } 195 196 // Get context data 197 CeedCallBackend(CeedQFunctionGetInnerContextData(qf, CEED_MEM_DEVICE, &qf_data->d_c)); 198 199 // Apply operator 200 void *opargs[] = {(void *)&num_elem, &qf_data->d_c, &data->indices, &data->fields, &data->B, &data->G, &data->W, &data->points}; 201 int max_threads_per_block, min_grid_size, grid; 202 203 CeedCallBackend(CeedOperatorHasTensorBases(op, &is_tensor)); 204 const CeedInt thread_1d = CeedIntMax(is_tensor ? data->Q_1d : data->Q, data->max_P_1d); 205 206 CeedCallCuda(ceed, cuOccupancyMaxPotentialBlockSize(&min_grid_size, &max_threads_per_block, data->op, dynamicSMemSize, 0, 0x10000)); 207 int block[3] = {thread_1d, ((!is_tensor || data->dim == 1) ? 1 : thread_1d), -1}; 208 209 if (is_tensor) { 210 CeedCallBackend(BlockGridCalculate(num_elem, min_grid_size / cuda_data->device_prop.multiProcessorCount, is_at_points ? 1 : max_threads_per_block, 211 cuda_data->device_prop.maxThreadsDim[2], cuda_data->device_prop.warpSize, block, &grid)); 212 } else { 213 CeedInt elems_per_block = CeedIntMin(cuda_data->device_prop.maxThreadsDim[2], CeedIntMax(512 / thread_1d, 1)); 214 215 grid = num_elem / elems_per_block + (num_elem % elems_per_block > 0); 216 block[2] = elems_per_block; 217 } 218 CeedInt shared_mem = block[0] * block[1] * block[2] * sizeof(CeedScalar); 219 220 CeedCallBackend(CeedTryRunKernelDimShared_Cuda(ceed, data->op, stream, grid, block[0], block[1], block[2], shared_mem, is_run_good, opargs)); 221 222 // Restore input arrays 223 for (CeedInt i = 0; i < num_input_fields; i++) { 224 CeedCallBackend(CeedQFunctionFieldGetEvalMode(qf_input_fields[i], &eval_mode)); 225 if (eval_mode == CEED_EVAL_WEIGHT) { // Skip 226 } else { 227 bool is_active; 228 CeedVector vec; 229 230 CeedCallBackend(CeedOperatorFieldGetVector(op_input_fields[i], &vec)); 231 is_active = vec == CEED_VECTOR_ACTIVE; 232 if (!is_active) CeedCallBackend(CeedVectorRestoreArrayRead(vec, &data->fields.inputs[i])); 233 CeedCallBackend(CeedVectorDestroy(&vec)); 234 } 235 } 236 237 // Restore output arrays 238 for (CeedInt i = 0; i < num_output_fields; i++) { 239 CeedCallBackend(CeedQFunctionFieldGetEvalMode(qf_output_fields[i], &eval_mode)); 240 if (eval_mode == CEED_EVAL_WEIGHT) { // Skip 241 } else { 242 bool is_active; 243 CeedVector vec; 244 245 CeedCallBackend(CeedOperatorFieldGetVector(op_output_fields[i], &vec)); 246 is_active = vec == CEED_VECTOR_ACTIVE; 247 if (!is_active) CeedCallBackend(CeedVectorRestoreArray(vec, &data->fields.outputs[i])); 248 CeedCallBackend(CeedVectorDestroy(&vec)); 249 } 250 } 251 252 // Restore point coordinates, if needed 253 if (is_at_points) { 254 CeedVector vec; 255 256 CeedCallBackend(CeedOperatorAtPointsGetPoints(op, NULL, &vec)); 257 CeedCallBackend(CeedVectorRestoreArrayRead(vec, &data->points.coords)); 258 CeedCallBackend(CeedVectorDestroy(&vec)); 259 } 260 261 // Restore context data 262 CeedCallBackend(CeedQFunctionRestoreInnerContextData(qf, &qf_data->d_c)); 263 264 // Cleanup 265 CeedCallBackend(CeedDestroy(&ceed)); 266 CeedCallBackend(CeedQFunctionDestroy(&qf)); 267 if (!(*is_run_good)) data->use_fallback = true; 268 return CEED_ERROR_SUCCESS; 269 } 270 271 static int CeedOperatorApplyAdd_Cuda_gen(CeedOperator op, CeedVector input_vec, CeedVector output_vec, CeedRequest *request) { 272 bool is_run_good = false; 273 const CeedScalar *input_arr = NULL; 274 CeedScalar *output_arr = NULL; 275 276 // Try to run kernel 277 if (input_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorGetArrayRead(input_vec, CEED_MEM_DEVICE, &input_arr)); 278 if (output_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorGetArray(output_vec, CEED_MEM_DEVICE, &output_arr)); 279 CeedCallBackend(CeedOperatorApplyAddCore_Cuda_gen(op, NULL, input_arr, output_arr, &is_run_good, request)); 280 if (input_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorRestoreArrayRead(input_vec, &input_arr)); 281 if (output_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorRestoreArray(output_vec, &output_arr)); 282 283 // Fallback on unsuccessful run 284 if (!is_run_good) { 285 CeedOperator op_fallback; 286 287 CeedDebug256(CeedOperatorReturnCeed(op), CEED_DEBUG_COLOR_SUCCESS, "Falling back to /gpu/cuda/ref CeedOperator"); 288 CeedCallBackend(CeedOperatorGetFallback(op, &op_fallback)); 289 CeedCallBackend(CeedOperatorApplyAdd(op_fallback, input_vec, output_vec, request)); 290 } 291 return CEED_ERROR_SUCCESS; 292 } 293 294 static int CeedOperatorApplyAddComposite_Cuda_gen(CeedOperator op, CeedVector input_vec, CeedVector output_vec, CeedRequest *request) { 295 bool is_run_good[CEED_COMPOSITE_MAX] = {false}; 296 CeedInt num_suboperators; 297 const CeedScalar *input_arr = NULL; 298 CeedScalar *output_arr = NULL; 299 Ceed ceed; 300 CeedOperator *sub_operators; 301 302 CeedCallBackend(CeedOperatorGetCeed(op, &ceed)); 303 CeedCall(CeedCompositeOperatorGetNumSub(op, &num_suboperators)); 304 CeedCall(CeedCompositeOperatorGetSubList(op, &sub_operators)); 305 if (input_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorGetArrayRead(input_vec, CEED_MEM_DEVICE, &input_arr)); 306 if (output_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorGetArray(output_vec, CEED_MEM_DEVICE, &output_arr)); 307 for (CeedInt i = 0; i < num_suboperators; i++) { 308 CeedInt num_elem = 0; 309 310 CeedCall(CeedOperatorGetNumElements(sub_operators[i], &num_elem)); 311 if (num_elem > 0) { 312 cudaStream_t stream = NULL; 313 314 CeedCallCuda(ceed, cudaStreamCreate(&stream)); 315 CeedCallBackend(CeedOperatorApplyAddCore_Cuda_gen(sub_operators[i], stream, input_arr, output_arr, &is_run_good[i], request)); 316 CeedCallCuda(ceed, cudaStreamDestroy(stream)); 317 } 318 } 319 if (input_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorRestoreArrayRead(input_vec, &input_arr)); 320 if (output_vec != CEED_VECTOR_NONE) CeedCallBackend(CeedVectorRestoreArray(output_vec, &output_arr)); 321 CeedCallCuda(ceed, cudaDeviceSynchronize()); 322 323 // Fallback on unsuccessful run 324 for (CeedInt i = 0; i < num_suboperators; i++) { 325 if (!is_run_good[i]) { 326 CeedOperator op_fallback; 327 328 CeedDebug256(ceed, CEED_DEBUG_COLOR_SUCCESS, "Falling back to /gpu/cuda/ref CeedOperator"); 329 CeedCallBackend(CeedOperatorGetFallback(sub_operators[i], &op_fallback)); 330 CeedCallBackend(CeedOperatorApplyAdd(op_fallback, input_vec, output_vec, request)); 331 } 332 } 333 CeedCallBackend(CeedDestroy(&ceed)); 334 return CEED_ERROR_SUCCESS; 335 } 336 337 //------------------------------------------------------------------------------ 338 // Create operator 339 //------------------------------------------------------------------------------ 340 int CeedOperatorCreate_Cuda_gen(CeedOperator op) { 341 bool is_composite; 342 Ceed ceed; 343 CeedOperator_Cuda_gen *impl; 344 345 CeedCallBackend(CeedOperatorGetCeed(op, &ceed)); 346 CeedCallBackend(CeedCalloc(1, &impl)); 347 CeedCallBackend(CeedOperatorSetData(op, impl)); 348 CeedCall(CeedOperatorIsComposite(op, &is_composite)); 349 if (is_composite) { 350 CeedCallBackend(CeedSetBackendFunction(ceed, "Operator", op, "ApplyAddComposite", CeedOperatorApplyAddComposite_Cuda_gen)); 351 } else { 352 CeedCallBackend(CeedSetBackendFunction(ceed, "Operator", op, "ApplyAdd", CeedOperatorApplyAdd_Cuda_gen)); 353 } 354 CeedCallBackend(CeedSetBackendFunction(ceed, "Operator", op, "Destroy", CeedOperatorDestroy_Cuda_gen)); 355 CeedCallBackend(CeedDestroy(&ceed)); 356 return CEED_ERROR_SUCCESS; 357 } 358 359 //------------------------------------------------------------------------------ 360