1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
| #include <cassert> #include <functional> #include <iostream> #include <string> #include <vector>
#include <cooperative_groups.h> #include <cuda_runtime.h>
#define CHECK_CUDA_ERROR(val) check((val), #val, __FILE__, __LINE__) void check(cudaError_t err, char const* func, char const* file, int line) { if (err != cudaSuccess) { std::cerr << "CUDA Runtime Error at: " << file << ":" << line << std::endl; std::cerr << cudaGetErrorString(err) << " " << func << std::endl; std::exit(EXIT_FAILURE); } }
#define CHECK_LAST_CUDA_ERROR() check_last(__FILE__, __LINE__) void check_last(char const* file, int line) { cudaError_t const err{cudaGetLastError()}; if (err != cudaSuccess) { std::cerr << "CUDA Runtime Error at: " << file << ":" << line << std::endl; std::cerr << cudaGetErrorString(err) << std::endl; std::exit(EXIT_FAILURE); } }
template <class T> float measure_performance(std::function<T(cudaStream_t)> bound_function, cudaStream_t stream, size_t num_repeats = 10, size_t num_warmups = 10) { cudaEvent_t start, stop; float time;
CHECK_CUDA_ERROR(cudaEventCreate(&start)); CHECK_CUDA_ERROR(cudaEventCreate(&stop));
for (size_t i{0}; i < num_warmups; ++i) { bound_function(stream); }
CHECK_CUDA_ERROR(cudaStreamSynchronize(stream));
CHECK_CUDA_ERROR(cudaEventRecord(start, stream)); for (size_t i{0}; i < num_repeats; ++i) { bound_function(stream); } CHECK_CUDA_ERROR(cudaEventRecord(stop, stream)); CHECK_CUDA_ERROR(cudaEventSynchronize(stop)); CHECK_LAST_CUDA_ERROR(); CHECK_CUDA_ERROR(cudaEventElapsedTime(&time, start, stop)); CHECK_CUDA_ERROR(cudaEventDestroy(start)); CHECK_CUDA_ERROR(cudaEventDestroy(stop));
float const latency{time / num_repeats};
return latency; }
std::string std_string_centered(std::string const& s, size_t width, char pad = ' ') { size_t const l{s.length()}; if (width < l) { throw std::runtime_error("Width is too small."); } size_t const left_pad{(width - l) / 2}; size_t const right_pad{width - l - left_pad}; std::string const s_centered{std::string(left_pad, pad) + s + std::string(right_pad, pad)}; return s_centered; }
template <size_t NUM_THREADS> __device__ float thread_block_reduce_sum( cooperative_groups::thread_block_tile<NUM_THREADS> group, float shared_data[NUM_THREADS], float val) { static_assert(NUM_THREADS % 32 == 0, "NUM_THREADS must be a multiple of 32"); size_t thread_idx{group.thread_rank()}; shared_data[thread_idx] = val; group.sync(); #pragma unroll for (size_t offset{group.size() / 2}; offset > 0; offset /= 2) { if (thread_idx < offset) { shared_data[thread_idx] += shared_data[thread_idx + offset]; } group.sync(); } return shared_data[0]; }
__device__ float thread_block_reduce_sum(cooperative_groups::thread_block group, float* shared_data, float val) { size_t const thread_idx{group.thread_rank()}; shared_data[thread_idx] = val; group.sync(); for (size_t stride{group.size() / 2}; stride > 0; stride /= 2) { if (thread_idx < stride) { shared_data[thread_idx] += shared_data[thread_idx + stride]; } group.sync(); } return shared_data[0]; }
template <size_t NUM_WARPS> __device__ float thread_block_reduce_sum(float shared_data[NUM_WARPS]) { float sum{0.0f}; #pragma unroll for (size_t i{0}; i < NUM_WARPS; ++i) { sum += shared_data[i]; } return sum; }
__device__ float thread_reduce_sum(float const* __restrict__ input_data, size_t start_offset, size_t num_elements, size_t stride) { float sum{0.0f}; for (size_t i{start_offset}; i < num_elements; i += stride) { sum += input_data[i]; } return sum; }
__device__ float warp_reduce_sum(cooperative_groups::thread_block_tile<32> group, float val) { #pragma unroll for (size_t offset{group.size() / 2}; offset > 0; offset /= 2) { val += group.shfl_down(val, offset); } return val; }
template <size_t NUM_THREADS> __device__ float thread_block_reduce_sum_v1(float const* __restrict__ input_data, size_t num_elements) { static_assert(NUM_THREADS % 32 == 0, "NUM_THREADS must be a multiple of 32"); __shared__ float shared_data[NUM_THREADS]; size_t const thread_idx{ cooperative_groups::this_thread_block().thread_index().x}; float sum{ thread_reduce_sum(input_data, thread_idx, num_elements, NUM_THREADS)}; shared_data[thread_idx] = sum; float const block_sum{thread_block_reduce_sum( cooperative_groups::this_thread_block(), shared_data, sum)}; return block_sum; }
template <size_t NUM_THREADS, size_t NUM_WARPS = NUM_THREADS / 32> __device__ float thread_block_reduce_sum_v2(float const* __restrict__ input_data, size_t num_elements) { static_assert(NUM_THREADS % 32 == 0, "NUM_THREADS must be a multiple of 32"); __shared__ float shared_data[NUM_WARPS]; size_t const thread_idx{ cooperative_groups::this_thread_block().thread_index().x}; float sum{ thread_reduce_sum(input_data, thread_idx, num_elements, NUM_THREADS)}; cooperative_groups::thread_block_tile<32> const warp{ cooperative_groups::tiled_partition<32>( cooperative_groups::this_thread_block())}; sum = warp_reduce_sum(warp, sum); if (warp.thread_rank() == 0) { shared_data[cooperative_groups::this_thread_block().thread_rank() / 32] = sum; } cooperative_groups::this_thread_block().sync(); float const block_sum{thread_block_reduce_sum<NUM_WARPS>(shared_data)}; return block_sum; }
template <size_t NUM_THREADS> __global__ void batched_reduce_sum_v1(float* __restrict__ output_data, float const* __restrict__ input_data, size_t num_elements_per_batch) { static_assert(NUM_THREADS % 32 == 0, "NUM_THREADS must be a multiple of 32"); size_t const block_idx{cooperative_groups::this_grid().block_rank()}; size_t const thread_idx{ cooperative_groups::this_thread_block().thread_rank()}; float const block_sum{thread_block_reduce_sum_v1<NUM_THREADS>( input_data + block_idx * num_elements_per_batch, num_elements_per_batch)}; if (thread_idx == 0) { output_data[block_idx] = block_sum; } }
template <size_t NUM_THREADS> __global__ void batched_reduce_sum_v2(float* __restrict__ output_data, float const* __restrict__ input_data, size_t num_elements_per_batch) { static_assert(NUM_THREADS % 32 == 0, "NUM_THREADS must be a multiple of 32"); constexpr size_t NUM_WARPS{NUM_THREADS / 32}; size_t const block_idx{cooperative_groups::this_grid().block_rank()}; size_t const thread_idx{ cooperative_groups::this_thread_block().thread_rank()}; float const block_sum{thread_block_reduce_sum_v2<NUM_THREADS, NUM_WARPS>( input_data + block_idx * num_elements_per_batch, num_elements_per_batch)}; if (thread_idx == 0) { output_data[block_idx] = block_sum; } }
template <size_t NUM_THREADS, size_t NUM_BLOCK_ELEMENTS> __global__ void full_reduce_sum(float* output, float const* __restrict__ input_data, size_t num_elements, float* workspace) { static_assert(NUM_THREADS % 32 == 0, "NUM_THREADS must be a multiple of 32"); static_assert(NUM_BLOCK_ELEMENTS % NUM_THREADS == 0, "NUM_BLOCK_ELEMENTS must be a multiple of NUM_THREADS"); size_t const num_grid_elements{ NUM_BLOCK_ELEMENTS * cooperative_groups::this_grid().num_blocks()}; float* const workspace_ptr_1{workspace}; float* const workspace_ptr_2{workspace + num_elements / 2}; size_t remaining_elements{num_elements};
float* workspace_output_data{workspace_ptr_1}; size_t const num_grid_iterations{ (remaining_elements + num_grid_elements - 1) / num_grid_elements}; for (size_t i{0}; i < num_grid_iterations; ++i) { size_t const grid_offset{i * num_grid_elements}; size_t const block_offset{grid_offset + cooperative_groups::this_grid().block_rank() * NUM_BLOCK_ELEMENTS}; size_t const num_actual_elements_to_reduce_per_block{ remaining_elements >= block_offset ? min(NUM_BLOCK_ELEMENTS, remaining_elements - block_offset) : 0}; float const block_sum{thread_block_reduce_sum_v1<NUM_THREADS>( input_data + block_offset, num_actual_elements_to_reduce_per_block)}; if (cooperative_groups::this_thread_block().thread_rank() == 0) { workspace_output_data [i * cooperative_groups::this_grid().num_blocks() + cooperative_groups::this_grid().block_rank()] = block_sum; } } cooperative_groups::this_grid().sync(); remaining_elements = (remaining_elements + NUM_BLOCK_ELEMENTS - 1) / NUM_BLOCK_ELEMENTS;
float* workspace_input_data{workspace_output_data}; workspace_output_data = workspace_ptr_2; while (remaining_elements > 1) { size_t const num_grid_iterations{ (remaining_elements + num_grid_elements - 1) / num_grid_elements}; for (size_t i{0}; i < num_grid_iterations; ++i) { size_t const grid_offset{i * num_grid_elements}; size_t const block_offset{ grid_offset + cooperative_groups::this_grid().block_rank() * NUM_BLOCK_ELEMENTS}; size_t const num_actual_elements_to_reduce_per_block{ remaining_elements >= block_offset ? min(NUM_BLOCK_ELEMENTS, remaining_elements - block_offset) : 0}; float const block_sum{thread_block_reduce_sum_v1<NUM_THREADS>( workspace_input_data + block_offset, num_actual_elements_to_reduce_per_block)}; if (cooperative_groups::this_thread_block().thread_rank() == 0) { workspace_output_data [i * cooperative_groups::this_grid().num_blocks() + cooperative_groups::this_grid().block_rank()] = block_sum; } } cooperative_groups::this_grid().sync(); remaining_elements = (remaining_elements + NUM_BLOCK_ELEMENTS - 1) / NUM_BLOCK_ELEMENTS;
float* const temp{workspace_input_data}; workspace_input_data = workspace_output_data; workspace_output_data = temp; }
workspace_output_data = workspace_input_data; if (cooperative_groups::this_grid().thread_rank() == 0) { *output = workspace_output_data[0]; } }
template <size_t NUM_THREADS> void launch_batched_reduce_sum_v1(float* output_data, float const* input_data, size_t batch_size, size_t num_elements_per_batch, cudaStream_t stream) { size_t const num_blocks{batch_size}; batched_reduce_sum_v1<NUM_THREADS><<<num_blocks, NUM_THREADS, 0, stream>>>( output_data, input_data, num_elements_per_batch); CHECK_LAST_CUDA_ERROR(); }
template <size_t NUM_THREADS> void launch_batched_reduce_sum_v2(float* output_data, float const* input_data, size_t batch_size, size_t num_elements_per_batch, cudaStream_t stream) { size_t const num_blocks{batch_size}; batched_reduce_sum_v2<NUM_THREADS><<<num_blocks, NUM_THREADS, 0, stream>>>( output_data, input_data, num_elements_per_batch); CHECK_LAST_CUDA_ERROR(); }
template <size_t NUM_THREADS, size_t NUM_BLOCK_ELEMENTS> void launch_full_reduce_sum(float* output, float const* input_data, size_t num_elements, float* workspace, cudaStream_t stream) { void const* func{reinterpret_cast<void const*>( full_reduce_sum<NUM_THREADS, NUM_BLOCK_ELEMENTS>)}; int dev{0}; cudaDeviceProp deviceProp; CHECK_CUDA_ERROR(cudaGetDeviceProperties(&deviceProp, dev)); dim3 const grid_dim{ static_cast<unsigned int>(deviceProp.multiProcessorCount)}; dim3 const block_dim{NUM_THREADS};
void* args[]{static_cast<void*>(&output), static_cast<void*>(&input_data), static_cast<void*>(&num_elements), static_cast<void*>(&workspace)}; CHECK_CUDA_ERROR(cudaLaunchCooperativeKernel(func, grid_dim, block_dim, args, 0, stream)); CHECK_LAST_CUDA_ERROR(); }
float profile_full_reduce_sum( std::function<void(float*, float const*, size_t, float*, cudaStream_t)> full_reduce_sum_launch_function, size_t num_elements) { cudaStream_t stream; CHECK_CUDA_ERROR(cudaStreamCreate(&stream));
constexpr float element_value{1.0f}; std::vector<float> input_data(num_elements, element_value); float output{0.0f};
float* d_input_data; float* d_workspace; float* d_output;
CHECK_CUDA_ERROR(cudaMalloc(&d_input_data, num_elements * sizeof(float))); CHECK_CUDA_ERROR(cudaMalloc(&d_workspace, num_elements * sizeof(float))); CHECK_CUDA_ERROR(cudaMalloc(&d_output, sizeof(float)));
CHECK_CUDA_ERROR(cudaMemcpy(d_input_data, input_data.data(), num_elements * sizeof(float), cudaMemcpyHostToDevice));
full_reduce_sum_launch_function(d_output, d_input_data, num_elements, d_workspace, stream); CHECK_CUDA_ERROR(cudaStreamSynchronize(stream));
CHECK_CUDA_ERROR( cudaMemcpy(&output, d_output, sizeof(float), cudaMemcpyDeviceToHost)); if (output != num_elements * element_value) { std::cout << "Expected: " << num_elements * element_value << " but got: " << output << std::endl; throw std::runtime_error("Error: incorrect sum"); } std::function<void(cudaStream_t)> const bound_function{ std::bind(full_reduce_sum_launch_function, d_output, d_input_data, num_elements, d_workspace, std::placeholders::_1)}; float const latency{measure_performance<void>(bound_function, stream)}; std::cout << "Latency: " << latency << " ms" << std::endl;
size_t num_bytes{num_elements * sizeof(float) + sizeof(float)}; float const bandwidth{(num_bytes * 1e-6f) / latency}; std::cout << "Effective Bandwidth: " << bandwidth << " GB/s" << std::endl;
CHECK_CUDA_ERROR(cudaFree(d_input_data)); CHECK_CUDA_ERROR(cudaFree(d_workspace)); CHECK_CUDA_ERROR(cudaFree(d_output)); CHECK_CUDA_ERROR(cudaStreamDestroy(stream));
return latency; }
float profile_batched_reduce_sum( std::function<void(float*, float const*, size_t, size_t, cudaStream_t)> batched_reduce_sum_launch_function, size_t batch_size, size_t num_elements_per_batch) { size_t const num_elements{batch_size * num_elements_per_batch};
cudaStream_t stream; CHECK_CUDA_ERROR(cudaStreamCreate(&stream));
constexpr float element_value{1.0f}; std::vector<float> input_data(num_elements, element_value); std::vector<float> output_data(batch_size, 0.0f);
float* d_input_data; float* d_output_data;
CHECK_CUDA_ERROR(cudaMalloc(&d_input_data, num_elements * sizeof(float))); CHECK_CUDA_ERROR(cudaMalloc(&d_output_data, batch_size * sizeof(float)));
CHECK_CUDA_ERROR(cudaMemcpy(d_input_data, input_data.data(), num_elements * sizeof(float), cudaMemcpyHostToDevice));
batched_reduce_sum_launch_function(d_output_data, d_input_data, batch_size, num_elements_per_batch, stream); CHECK_CUDA_ERROR(cudaStreamSynchronize(stream));
CHECK_CUDA_ERROR(cudaMemcpy(output_data.data(), d_output_data, batch_size * sizeof(float), cudaMemcpyDeviceToHost)); for (size_t i{0}; i < batch_size; ++i) { if (output_data.at(i) != num_elements_per_batch * element_value) { std::cout << "Expected: " << num_elements_per_batch * element_value << " but got: " << output_data.at(i) << std::endl; throw std::runtime_error("Error: incorrect sum"); } } std::function<void(cudaStream_t)> const bound_function{std::bind( batched_reduce_sum_launch_function, d_output_data, d_input_data, batch_size, num_elements_per_batch, std::placeholders::_1)}; float const latency{measure_performance<void>(bound_function, stream)}; std::cout << "Latency: " << latency << " ms" << std::endl;
size_t num_bytes{num_elements * sizeof(float) + batch_size * sizeof(float)}; float const bandwidth{(num_bytes * 1e-6f) / latency}; std::cout << "Effective Bandwidth: " << bandwidth << " GB/s" << std::endl;
CHECK_CUDA_ERROR(cudaFree(d_input_data)); CHECK_CUDA_ERROR(cudaFree(d_output_data)); CHECK_CUDA_ERROR(cudaStreamDestroy(stream));
return latency; }
int main() { size_t const batch_size{2048}; size_t const num_elements_per_batch{1024 * 256};
constexpr size_t string_width{50U}; std::cout << std_string_centered("", string_width, '~') << std::endl; std::cout << std_string_centered("NVIDIA GPU Device Info", string_width, ' ') << std::endl; std::cout << std_string_centered("", string_width, '~') << std::endl;
int device_id{0}; cudaGetDevice(&device_id); cudaDeviceProp device_prop; cudaGetDeviceProperties(&device_prop, device_id); std::cout << "Device Name: " << device_prop.name << std::endl; float const memory_size{static_cast<float>(device_prop.totalGlobalMem) / (1 << 30)}; std::cout << "Memory Size: " << memory_size << " GB" << std::endl; float const peak_bandwidth{ static_cast<float>(2.0f * device_prop.memoryClockRate * (device_prop.memoryBusWidth / 8) / 1.0e6)}; std::cout << "Peak Bandwitdh: " << peak_bandwidth << " GB/s" << std::endl;
std::cout << std_string_centered("", string_width, '~') << std::endl; std::cout << std_string_centered("Reduce Sum Profiling", string_width, ' ') << std::endl; std::cout << std_string_centered("", string_width, '~') << std::endl;
std::cout << std_string_centered("", string_width, '=') << std::endl; std::cout << "Batch Size: " << batch_size << std::endl; std::cout << "Number of Elements Per Batch: " << num_elements_per_batch << std::endl; std::cout << std_string_centered("", string_width, '=') << std::endl;
constexpr size_t NUM_THREADS_PER_BATCH{256}; static_assert(NUM_THREADS_PER_BATCH % 32 == 0, "NUM_THREADS_PER_BATCH must be a multiple of 32"); static_assert(NUM_THREADS_PER_BATCH <= 1024, "NUM_THREADS_PER_BATCH must be less than or equal to 1024");
std::cout << "Batched Reduce Sum V1" << std::endl; float const latency_v1{profile_batched_reduce_sum( launch_batched_reduce_sum_v1<NUM_THREADS_PER_BATCH>, batch_size, num_elements_per_batch)}; std::cout << std_string_centered("", string_width, '-') << std::endl;
std::cout << "Batched Reduce Sum V2" << std::endl; float const latency_v2{profile_batched_reduce_sum( launch_batched_reduce_sum_v2<NUM_THREADS_PER_BATCH>, batch_size, num_elements_per_batch)}; std::cout << std_string_centered("", string_width, '-') << std::endl;
std::cout << "Full Reduce Sum" << std::endl; constexpr size_t NUM_THREADS{256}; constexpr size_t NUM_BLOCK_ELEMENTS{NUM_THREADS * 1024}; float const latency_v3{profile_full_reduce_sum( launch_full_reduce_sum<NUM_THREADS, NUM_BLOCK_ELEMENTS>, batch_size * num_elements_per_batch)}; std::cout << std_string_centered("", string_width, '-') << std::endl; }
|