mirror of
https://github.com/NVIDIA/cuda-samples.git
synced 2026-10-13 00:08:26 +08:00
CUDA 13.2 samples update (#432)
- Added Python samples for CUDA Python 1.0 release - Renamed top-level `Samples` directory to `cpp` to accommodate Python samples.
This commit is contained in:
24
cpp/3_CUDA_Features/CMakeLists.txt
Normal file
24
cpp/3_CUDA_Features/CMakeLists.txt
Normal file
@@ -0,0 +1,24 @@
|
||||
add_subdirectory(StreamPriorities)
|
||||
add_subdirectory(bf16TensorCoreGemm)
|
||||
add_subdirectory(binaryPartitionCG)
|
||||
add_subdirectory(bindlessTexture)
|
||||
add_subdirectory(cdpAdvancedQuicksort)
|
||||
add_subdirectory(cdpBezierTessellation)
|
||||
add_subdirectory(cdpQuadtree)
|
||||
add_subdirectory(cdpSimplePrint)
|
||||
add_subdirectory(cdpSimpleQuicksort)
|
||||
add_subdirectory(cudaCompressibleMemory)
|
||||
add_subdirectory(cudaTensorCoreGemm)
|
||||
add_subdirectory(dmmaTensorCoreGemm)
|
||||
add_subdirectory(globalToShmemAsyncCopy)
|
||||
add_subdirectory(graphConditionalNodes)
|
||||
add_subdirectory(graphMemoryFootprint)
|
||||
add_subdirectory(graphMemoryNodes)
|
||||
add_subdirectory(immaTensorCoreGemm)
|
||||
add_subdirectory(jacobiCudaGraphs)
|
||||
add_subdirectory(memMapIPCDrv)
|
||||
add_subdirectory(newdelete)
|
||||
add_subdirectory(ptxjit)
|
||||
add_subdirectory(simpleCudaGraphs)
|
||||
add_subdirectory(tf32TensorCoreGemm)
|
||||
add_subdirectory(warpAggregatedAtomicsCG)
|
||||
78
cpp/3_CUDA_Features/README.md
Normal file
78
cpp/3_CUDA_Features/README.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# 3. CUDA Features
|
||||
|
||||
|
||||
### [bf16TensorCoreGemm](./bf16TensorCoreGemm)
|
||||
A CUDA sample demonstrating __nv_bfloat16 (e8m7) GEMM computation using the Warp Matrix Multiply and Accumulate (WMMA) API introduced with CUDA 11 in Ampere chip family tensor cores for faster matrix operations. This sample also uses async copy provided by cuda pipeline interface for gmem to shmem async loads which improves kernel performance and reduces register presssure.
|
||||
|
||||
### [binaryPartitionCG](./binaryPartitionCG)
|
||||
This sample is a simple code that illustrates binary partition cooperative groups and reduce within the thread block.
|
||||
|
||||
### [bindlessTexture](./bindlessTexture)
|
||||
This example demonstrates use of cudaSurfaceObject, cudaTextureObject, and MipMap support in CUDA. A GPU with Compute Capability SM 3.0 is required to run the sample.
|
||||
|
||||
### [cdpAdvancedQuicksort](./cdpAdvancedQuicksort)
|
||||
This sample demonstrates an advanced quicksort implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
### [cdpBezierTessellation](./cdpBezierTessellation)
|
||||
This sample demonstrates bezier tessellation of lines implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
### [cdpQuadtree](./cdpQuadtree)
|
||||
This sample demonstrates Quad Trees implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
### [cdpSimplePrint](./cdpSimplePrint)
|
||||
This sample demonstrates simple printf implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
### [cdpSimpleQuicksort](./cdpSimpleQuicksort)
|
||||
This sample demonstrates simple quicksort implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
### [cudaCompressibleMemory](./cudaCompressibleMemory)
|
||||
This sample demonstrates the compressible memory allocation using cuMemMap API.
|
||||
|
||||
### [cudaTensorCoreGemm](./cudaTensorCoreGemm)
|
||||
CUDA sample demonstrating a GEMM computation using the Warp Matrix Multiply and Accumulate (WMMA) API introduced in CUDA 9.
|
||||
|
||||
This sample demonstrates the use of the new CUDA WMMA API employing the Tensor Cores introduced in the Volta chip family for faster matrix operations.
|
||||
|
||||
In addition to that, it demonstrates the use of the new CUDA function attribute cudaFuncAttributeMaxDynamicSharedMemorySize that allows the application to reserve an extended amount of shared memory than it is available by default.
|
||||
|
||||
### [dmmaTensorCoreGemm](./dmmaTensorCoreGemm)
|
||||
CUDA sample demonstrates double precision GEMM computation using the Double precision Warp Matrix Multiply and Accumulate (WMMA) API introduced with CUDA 11 in Ampere chip family tensor cores for faster matrix operations. This sample also uses async copy provided by cuda pipeline interface for gmem to shmem async loads which improves kernel performance and reduces register presssure. Further, this sample also demonstrates how to use cooperative groups async copy interface over a group for performing gmem to shmem async loads.
|
||||
|
||||
### [globalToShmemAsyncCopy](./globalToShmemAsyncCopy)
|
||||
This sample implements matrix multiplication which uses asynchronous copy of data from global to shared memory when on compute capability 8.0 or higher. Also demonstrates arrive-wait barrier for synchronization.
|
||||
|
||||
### [graphMemoryFootprint](./graphMemoryFootprint)
|
||||
This sample demonstrates how graph memory nodes re-use virtual addresses and physical memory.
|
||||
|
||||
### [graphMemoryNodes](./graphMemoryNodes)
|
||||
A demonstration of memory allocations and frees within CUDA graphs using Graph APIs and Stream Capture APIs.
|
||||
|
||||
### [immaTensorCoreGemm](./immaTensorCoreGemm)
|
||||
CUDA sample demonstrating a integer GEMM computation using the Warp Matrix Multiply and Accumulate (WMMA) API for integer introduced in CUDA 10. This sample demonstrates the use of the CUDA WMMA API employing the Tensor Cores introduced in the Volta chip family for faster matrix operations. In addition to that, it demonstrates the use of the new CUDA function attribute cudaFuncAttributeMaxDynamicSharedMemorySize that allows the application to reserve an extended amount of shared memory than it is available by default.
|
||||
|
||||
### [jacobiCudaGraphs](./jacobiCudaGraphs)
|
||||
Demonstrates Instantiated CUDA Graph Update with Jacobi Iterative Method using cudaGraphExecKernelNodeSetParams() and cudaGraphExecUpdate() approach.
|
||||
|
||||
### [memMapIPCDrv](./memMapIPCDrv)
|
||||
This CUDA Driver API sample is a very basic sample that demonstrates Inter Process Communication using cuMemMap APIs with one process per GPU for computation. Requires Compute Capability 3.0 or higher and a Linux Operating System, or a Windows Operating System
|
||||
|
||||
### [newdelete](./newdelete)
|
||||
This sample demonstrates dynamic global memory allocation through device C++ new and delete operators and virtual function declarations available with CUDA 4.0.
|
||||
|
||||
### [ptxjit](./ptxjit)
|
||||
This sample uses the Driver API to just-in-time compile (JIT) a Kernel from PTX code. Additionally, this sample demonstrates the seamless interoperability capability of the CUDA Runtime and CUDA Driver API calls. For CUDA 5.5, this sample shows how to use cuLink* functions to link PTX assembly using the CUDA driver at runtime.
|
||||
|
||||
### [simpleCudaGraphs](./simpleCudaGraphs)
|
||||
A demonstration of CUDA Graphs creation, instantiation and launch using Graphs APIs and Stream Capture APIs.
|
||||
|
||||
### [StreamPriorities](./StreamPriorities)
|
||||
This sample demonstrates basic use of stream priorities.
|
||||
|
||||
### [tf32TensorCoreGemm](./tf32TensorCoreGemm)
|
||||
A CUDA sample demonstrating tf32 (e8m10) GEMM computation using the Warp Matrix Multiply and Accumulate (WMMA) API introduced with CUDA 11 in Ampere chip family tensor cores for faster matrix operations. This sample also uses async copy provided by cuda pipeline interface for gmem to shmem async loads which improves kernel performance and reduces register presssure.
|
||||
|
||||
### [warpAggregatedAtomicsCG](./warpAggregatedAtomicsCG)
|
||||
This sample demonstrates how using Cooperative Groups (CG) to perform warp aggregated atomics to single and multiple counters, a useful technique to improve performance when many threads atomically add to a single or multiple counters.
|
||||
|
||||
### [graphConditionalNodes](./graphConditionalNodes)
|
||||
Demonstrate the use of CUDA Graph conditional nodes available starting in CUDA 12.4.
|
||||
18
cpp/3_CUDA_Features/StreamPriorities/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/StreamPriorities/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/StreamPriorities/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/StreamPriorities/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
42
cpp/3_CUDA_Features/StreamPriorities/CMakeLists.txt
Normal file
42
cpp/3_CUDA_Features/StreamPriorities/CMakeLists.txt
Normal file
@@ -0,0 +1,42 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(StreamPriorities LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
# Source file
|
||||
# Add target for StreamPriorities
|
||||
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
|
||||
message(STATUS "Will not build sample streamPriorities - not supported on aarch64")
|
||||
else()
|
||||
add_executable(StreamPriorities StreamPriorities.cu)
|
||||
|
||||
target_compile_options(StreamPriorities PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(StreamPriorities PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(StreamPriorities PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
endif()
|
||||
else()
|
||||
message(STATUS "Will not build sample StreamPriorities - requires Linux OS")
|
||||
endif()
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
34
cpp/3_CUDA_Features/StreamPriorities/README.md
Normal file
34
cpp/3_CUDA_Features/StreamPriorities/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# StreamPriorities - Stream Priorities
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates basic use of stream priorities.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Streams and Events
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, ppc64le
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaStreamCreateWithPriority, cudaDeviceGetStreamPriorityRange, cudaEventSynchronize, cudaEventRecord, cudaMalloc, cudaEventElapsedTime, cudaGetDeviceProperties, cudaEventCreate
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[Stream-Priorities](../../../README.md#stream-priorities)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
193
cpp/3_CUDA_Features/StreamPriorities/StreamPriorities.cu
Normal file
193
cpp/3_CUDA_Features/StreamPriorities/StreamPriorities.cu
Normal file
@@ -0,0 +1,193 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// std::system includes
|
||||
#include <cstdio>
|
||||
|
||||
// CUDA-C includes
|
||||
#include <cuda_runtime.h>
|
||||
#include <helper_cuda.h>
|
||||
|
||||
#define TOTAL_SIZE 256 * 1024 * 1024
|
||||
#define EACH_SIZE 128 * 1024 * 1024
|
||||
|
||||
// # threadblocks
|
||||
#define TBLOCKS 1024
|
||||
#define THREADS 512
|
||||
|
||||
// throw error on equality
|
||||
#define ERR_EQ(X, Y) \
|
||||
do { \
|
||||
if ((X) == (Y)) { \
|
||||
fprintf(stderr, "Error in %s at %s:%d\n", __func__, __FILE__, __LINE__); \
|
||||
exit(-1); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
// throw error on difference
|
||||
#define ERR_NE(X, Y) \
|
||||
do { \
|
||||
if ((X) != (Y)) { \
|
||||
fprintf(stderr, "Error in %s at %s:%d\n", __func__, __FILE__, __LINE__); \
|
||||
exit(-1); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
// copy from source -> destination arrays
|
||||
__global__ void memcpy_kernel(int *dst, int *src, size_t n)
|
||||
{
|
||||
int num = gridDim.x * blockDim.x;
|
||||
int id = blockDim.x * blockIdx.x + threadIdx.x;
|
||||
|
||||
for (int i = id; i < n / sizeof(int); i += num) {
|
||||
dst[i] = src[i];
|
||||
}
|
||||
}
|
||||
|
||||
// initialise memory
|
||||
void mem_init(int *buf, size_t n)
|
||||
{
|
||||
for (int i = 0; i < n / sizeof(int); i++) {
|
||||
buf[i] = i;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
cudaDeviceProp device_prop;
|
||||
int dev_id;
|
||||
|
||||
printf("Starting [%s]...\n", argv[0]);
|
||||
|
||||
// set device
|
||||
dev_id = findCudaDevice(argc, (const char **)argv);
|
||||
checkCudaErrors(cudaGetDeviceProperties(&device_prop, dev_id));
|
||||
|
||||
if ((device_prop.major << 4) + device_prop.minor < 0x35) {
|
||||
fprintf(stderr,
|
||||
"%s requires Compute Capability of SM 3.5 or higher to "
|
||||
"run.\nexiting...\n",
|
||||
argv[0]);
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
// get the range of priorities available
|
||||
// [ greatest_priority, lowest_priority ]
|
||||
int priority_low;
|
||||
int priority_hi;
|
||||
checkCudaErrors(cudaDeviceGetStreamPriorityRange(&priority_low, &priority_hi));
|
||||
|
||||
printf("CUDA stream priority range: LOW: %d to HIGH: %d\n", priority_low, priority_hi);
|
||||
|
||||
// create streams with highest and lowest available priorities
|
||||
cudaStream_t st_low;
|
||||
cudaStream_t st_hi;
|
||||
checkCudaErrors(cudaStreamCreateWithPriority(&st_low, cudaStreamNonBlocking, priority_low));
|
||||
checkCudaErrors(cudaStreamCreateWithPriority(&st_hi, cudaStreamNonBlocking, priority_hi));
|
||||
|
||||
size_t size;
|
||||
size = TOTAL_SIZE;
|
||||
|
||||
// initialise host data
|
||||
int *h_src_low;
|
||||
int *h_src_hi;
|
||||
ERR_EQ(h_src_low = (int *)malloc(size), NULL);
|
||||
ERR_EQ(h_src_hi = (int *)malloc(size), NULL);
|
||||
mem_init(h_src_low, size);
|
||||
mem_init(h_src_hi, size);
|
||||
|
||||
// initialise device data
|
||||
int *h_dst_low;
|
||||
int *h_dst_hi;
|
||||
ERR_EQ(h_dst_low = (int *)malloc(size), NULL);
|
||||
ERR_EQ(h_dst_hi = (int *)malloc(size), NULL);
|
||||
memset(h_dst_low, 0, size);
|
||||
memset(h_dst_hi, 0, size);
|
||||
|
||||
// copy source data -> device
|
||||
int *d_src_low;
|
||||
int *d_src_hi;
|
||||
checkCudaErrors(cudaMalloc(&d_src_low, size));
|
||||
checkCudaErrors(cudaMalloc(&d_src_hi, size));
|
||||
checkCudaErrors(cudaMemcpy(d_src_low, h_src_low, size, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(d_src_hi, h_src_hi, size, cudaMemcpyHostToDevice));
|
||||
|
||||
// allocate memory for memcopy destination
|
||||
int *d_dst_low;
|
||||
int *d_dst_hi;
|
||||
checkCudaErrors(cudaMalloc(&d_dst_low, size));
|
||||
checkCudaErrors(cudaMalloc(&d_dst_hi, size));
|
||||
|
||||
// create some events
|
||||
cudaEvent_t ev_start_low;
|
||||
cudaEvent_t ev_start_hi;
|
||||
cudaEvent_t ev_end_low;
|
||||
cudaEvent_t ev_end_hi;
|
||||
checkCudaErrors(cudaEventCreate(&ev_start_low));
|
||||
checkCudaErrors(cudaEventCreate(&ev_start_hi));
|
||||
checkCudaErrors(cudaEventCreate(&ev_end_low));
|
||||
checkCudaErrors(cudaEventCreate(&ev_end_hi));
|
||||
|
||||
/* */
|
||||
|
||||
// call pair of kernels repeatedly (with different priority streams)
|
||||
checkCudaErrors(cudaEventRecord(ev_start_low, st_low));
|
||||
checkCudaErrors(cudaEventRecord(ev_start_hi, st_hi));
|
||||
|
||||
for (int i = 0; i < TOTAL_SIZE; i += EACH_SIZE) {
|
||||
int j = i / sizeof(int);
|
||||
memcpy_kernel<<<TBLOCKS, THREADS, 0, st_low>>>(d_dst_low + j, d_src_low + j, EACH_SIZE);
|
||||
memcpy_kernel<<<TBLOCKS, THREADS, 0, st_hi>>>(d_dst_hi + j, d_src_hi + j, EACH_SIZE);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaEventRecord(ev_end_low, st_low));
|
||||
checkCudaErrors(cudaEventRecord(ev_end_hi, st_hi));
|
||||
|
||||
checkCudaErrors(cudaEventSynchronize(ev_end_low));
|
||||
checkCudaErrors(cudaEventSynchronize(ev_end_hi));
|
||||
|
||||
/* */
|
||||
|
||||
size = TOTAL_SIZE;
|
||||
checkCudaErrors(cudaMemcpy(h_dst_low, d_dst_low, size, cudaMemcpyDeviceToHost));
|
||||
checkCudaErrors(cudaMemcpy(h_dst_hi, d_dst_hi, size, cudaMemcpyDeviceToHost));
|
||||
|
||||
// check results of kernels
|
||||
ERR_NE(memcmp(h_dst_low, h_src_low, size), 0);
|
||||
ERR_NE(memcmp(h_dst_hi, h_src_hi, size), 0);
|
||||
|
||||
// check timings
|
||||
float ms_low;
|
||||
float ms_hi;
|
||||
checkCudaErrors(cudaEventElapsedTime(&ms_low, ev_start_low, ev_end_low));
|
||||
checkCudaErrors(cudaEventElapsedTime(&ms_hi, ev_start_hi, ev_end_hi));
|
||||
|
||||
printf("elapsed time of kernels launched to LOW priority stream: %.3lf ms\n", ms_low);
|
||||
printf("elapsed time of kernels launched to HI priority stream: %.3lf ms\n", ms_hi);
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
18
cpp/3_CUDA_Features/bf16TensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/bf16TensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/bf16TensorCoreGemm/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/bf16TensorCoreGemm/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
39
cpp/3_CUDA_Features/bf16TensorCoreGemm/CMakeLists.txt
Normal file
39
cpp/3_CUDA_Features/bf16TensorCoreGemm/CMakeLists.txt
Normal file
@@ -0,0 +1,39 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(bf16TensorCoreGemm LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# This sample is not supported on QNX
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "QNX")
|
||||
message(STATUS "Will not build sample ${PROJECT_NAME} - not supported on QNX")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# Source file
|
||||
# Add target for bf16TensorCoreGemm
|
||||
add_executable(bf16TensorCoreGemm bf16TensorCoreGemm.cu)
|
||||
|
||||
target_compile_options(bf16TensorCoreGemm PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(bf16TensorCoreGemm PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(bf16TensorCoreGemm PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
36
cpp/3_CUDA_Features/bf16TensorCoreGemm/README.md
Normal file
36
cpp/3_CUDA_Features/bf16TensorCoreGemm/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# bf16TensorCoreGemm - bfloat16 Tensor Core GEMM
|
||||
|
||||
## Description
|
||||
|
||||
A CUDA sample demonstrating __nv_bfloat16 (e8m7) GEMM computation using the Warp Matrix Multiply and Accumulate (WMMA) API introduced with CUDA 11 in Ampere chip family tensor cores for faster matrix operations. This sample also uses async copy provided by cuda pipeline interface for gmem to shmem async loads which improves kernel performance and reduces register presssure.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Matrix Multiply, WMMA, Tensor Cores
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, aarch64
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaFree, cudaGetErrorString, cudaGetLastError, cudaEventSynchronize, cudaFuncSetAttribute, cudaEventRecord, cudaMemset, cudaMalloc, cudaEventElapsedTime, cudaGetDeviceProperties, cudaEventCreate
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[C++11 CUDA](../../../README.md#c11-cuda)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
845
cpp/3_CUDA_Features/bf16TensorCoreGemm/bf16TensorCoreGemm.cu
Normal file
845
cpp/3_CUDA_Features/bf16TensorCoreGemm/bf16TensorCoreGemm.cu
Normal file
@@ -0,0 +1,845 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// CUDA sample demonstrating a __nv_bfloat16 (E8M7) GEMM computation using the Warp Matrix Multiply
|
||||
// and Accumulate API introduced in CUDA 11.0.
|
||||
|
||||
// In this program, the compute_gemm kernel computes the result of a matrix multiplication
|
||||
// and addition: D = alpha * A * B + beta * C. The dimensions of both C and D matrices
|
||||
// are M_GLOBAL x N_GLOBAL. The A matrix is M_GLOBAL x K_GLOBAL (row-major), the B matrix
|
||||
// is K_GLOBAL x N_GLOBAL (column-major).
|
||||
// In that kernel, each CTA computes one 128 x 128 tile of the resulting matrix
|
||||
// per iteration. When the tile is computed, the CTA stores it to the global memory
|
||||
// and begins a new iteration, selecting a new 128 x 128 tile to compute.
|
||||
// Each CTA consists of eight warps. For the 128 x 128 tile, each warp computes eight
|
||||
// 16 x 16 subtiles, organized in a 2 x 4 two-dimensional array.
|
||||
// Warps compute the 16 x 16 subtiles using nvcuda::wmma::mma_sync operations by
|
||||
// moving through the K_GLOBAL dimension of the A and B matrices and accumulating
|
||||
// the intermediate result in the local thread state.
|
||||
|
||||
// There are a number of simple optimizations used in the algorithm:
|
||||
// - The CTA copies the 128 x 128 tile of the C matrix from the global memory to
|
||||
// shared memory. After that is done, each warp loads the C matrix fragments from
|
||||
// shared memory, thus avoiding a random global memory access.
|
||||
// - On each internal iteration, the CTA copies a portion of the A and B matrices from
|
||||
// global memory to shared memory. After that, all warps in the CTA reuse the A and B
|
||||
// data from shared memory, thus reducing the number of data copies from global memory.
|
||||
// - The portions of the A and B matrices are stored in shared memory with an additional
|
||||
// padding (skew) to reduce the number of shared memory access bank conflicts.
|
||||
// (See a detailed explanation near the SKEW_BF16 macro definition.)
|
||||
// - When the CTA finishes computing the tiles of the resulting matrix, each warp stores
|
||||
// its subtiles to shared memory. The CTA then copies the shared memory contents to
|
||||
// global memory, again avoiding redundant random global memory accesses.
|
||||
// - Note that the CTA tile size is chosen to maximize the GPU register utilization,
|
||||
// but carefully enough to avoid local memory use.
|
||||
|
||||
#include <assert.h>
|
||||
#include <cuda.h>
|
||||
#include <cuda/pipeline>
|
||||
#include <cuda_bf16.h>
|
||||
#include <mma.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// helper functions and utilities to work with CUDA
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_functions.h>
|
||||
|
||||
// Externally configurable parameters.
|
||||
|
||||
#ifndef CPU_DEBUG
|
||||
// Set this to 1 to verify the correctness of the GPU-computed matrix.
|
||||
#define CPU_DEBUG 0
|
||||
#endif
|
||||
|
||||
#ifndef SHARED_MEMORY_LIMIT_64K
|
||||
// Set this to 0 to use more than 64 Kb of shared memory to cache data, to
|
||||
// improve the performance of the computations on GPU.
|
||||
// Note that you need a GPU that can have more than 64 Kb of shared memory
|
||||
// per multiprocessor.
|
||||
#define SHARED_MEMORY_LIMIT_64K 0
|
||||
#endif
|
||||
|
||||
// GPU configuration.
|
||||
|
||||
#define WARP_SIZE 32
|
||||
|
||||
// MMA matrix tile dimensions.
|
||||
|
||||
#define M 16
|
||||
#define N 16
|
||||
#define K 16
|
||||
|
||||
// GEMM configuration.
|
||||
|
||||
#define M_TILES 512
|
||||
#define N_TILES 512
|
||||
#define K_TILES 512
|
||||
|
||||
#define M_GLOBAL (M * M_TILES)
|
||||
#define N_GLOBAL (N * N_TILES)
|
||||
#define K_GLOBAL (K * K_TILES)
|
||||
|
||||
#define C_LAYOUT wmma::mem_row_major
|
||||
|
||||
// Implementation constants.
|
||||
|
||||
#define WARPS_PER_BLOCK 8
|
||||
#define THREADS_PER_BLOCK (WARP_SIZE * WARPS_PER_BLOCK)
|
||||
|
||||
#if SHARED_MEMORY_LIMIT_64K
|
||||
// With only 64 Kb shared memory available, we can fit two 8-tile chunks of
|
||||
// the A and B matrix data, that is (M = 16) * (K = 16) * 8 * (CHUNK_K = 8)
|
||||
// * sizeof(__nv_bfloat16) = 32 Kb each.
|
||||
// (i.e. two 8x8 arrays of tiles of 16x16 __nv_bfloat16-typed elements per CTA).
|
||||
// But we cannot account the 8 Kb total skew overhead, without which the performance
|
||||
// would be severely impacted. So we choose to reduce the chunk size in half,
|
||||
// i.e. the amount of A and B matrix data we cache in shared memory.
|
||||
// Accordingly, this doubles the number of outer iterations across the global K
|
||||
// dimension, which only slightly impacts the performance.
|
||||
#define CHUNK_K 4
|
||||
#else
|
||||
#define CHUNK_K 8
|
||||
#endif
|
||||
|
||||
#define CHUNK_LINE_BYTES (CHUNK_K * K * sizeof(__nv_bfloat16))
|
||||
#define WARP_COPY_BYTES (WARP_SIZE * sizeof(int4))
|
||||
#define CHUNK_COPY_LINES_PER_WARP (WARP_COPY_BYTES / CHUNK_LINE_BYTES)
|
||||
#define CHUNK_COPY_LINE_LANES (WARP_SIZE / CHUNK_COPY_LINES_PER_WARP)
|
||||
|
||||
#define BLOCK_ROW_WARPS 2
|
||||
#define BLOCK_COL_WARPS 4
|
||||
|
||||
#define WARP_ROW_TILES 4
|
||||
#define WARP_COL_TILES 2
|
||||
|
||||
#define BLOCK_ROW_TILES (WARP_ROW_TILES * BLOCK_ROW_WARPS)
|
||||
#define BLOCK_COL_TILES (WARP_COL_TILES * BLOCK_COL_WARPS)
|
||||
|
||||
#define GLOBAL_MEM_STRIDE N_GLOBAL
|
||||
|
||||
#define SHMEM_STRIDE (N * BLOCK_ROW_TILES)
|
||||
#define SHMEM_OFFSET (N * WARP_ROW_TILES)
|
||||
|
||||
// The macro below is used to shift rows of the A matrix and columns of the B matrix
|
||||
// in shared memory to minimize possible bank conflicts.
|
||||
// Before performing the nvcuda::wmma::mma_sync operation, the warp must load the matrix
|
||||
// data using the nvcuda::wmma::load_matrix_sync operation. Although the memory access pattern
|
||||
// is not specified for that function, each lane in the warp can read one or multiple matrix
|
||||
// elements from different matrix rows or columns.
|
||||
// For shared memory, such access can result in bank conflicts if different rows / columns
|
||||
// of the matrix map to the same bank. By shifting each row and column by a few bytes, we
|
||||
// make sure that they map to different banks, thus reducing the number of possible bank
|
||||
// conflicts.
|
||||
// The number of 16 two-byte "__nv_bfloat16" elements is chosen as the minimum possible shift because
|
||||
// we must keep each row and column 256-bit aligned, as required by nvcuda::wmma::load_matrix_sync.
|
||||
#define SKEW_BF16 16
|
||||
|
||||
#define checkKernelErrors(expr) \
|
||||
do { \
|
||||
expr; \
|
||||
\
|
||||
cudaError_t __err = cudaGetLastError(); \
|
||||
if (__err != cudaSuccess) { \
|
||||
printf("Line %d: '%s' failed: %s\n", __LINE__, #expr, cudaGetErrorString(__err)); \
|
||||
abort(); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
enum kernels {
|
||||
bf16mma_shmem_gemm_async_copy = 0, // __nv_bfloat16 MMA shmem using kernel with async_copy
|
||||
bf16mma_shmem_gemm = 1, // __nv_bfloat16 MMA shmem using kernel normal copy (without async_copy).
|
||||
simple_bf16mma_gemm = 2 // __nv_bfloat16 MMA non-shmem using simple kernel.
|
||||
};
|
||||
|
||||
const char *kernelNames[] = {"compute_bf16gemm_async_copy", "compute_bf16gemm", "simple_wmma_bf16gemm"};
|
||||
|
||||
using namespace nvcuda;
|
||||
|
||||
__host__ void init_host_matrices(__nv_bfloat16 *a, __nv_bfloat16 *b, float *c)
|
||||
{
|
||||
for (int i = 0; i < M_GLOBAL; i++) {
|
||||
for (int j = 0; j < K_GLOBAL; j++) {
|
||||
a[i * K_GLOBAL + j] = (__nv_bfloat16)(float)(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < N_GLOBAL; i++) {
|
||||
for (int j = 0; j < K_GLOBAL; j++) {
|
||||
b[i * K_GLOBAL + j] = (__nv_bfloat16)(float)(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
for (int t = 0; t < M_GLOBAL * N_GLOBAL; t++) {
|
||||
c[t] = (float)(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void
|
||||
compute_bf16gemm(const __nv_bfloat16 *A, const __nv_bfloat16 *B, const float *C, float *D, float alpha, float beta)
|
||||
{
|
||||
#if __CUDA_ARCH__ >= 800
|
||||
extern __shared__ __nv_bfloat16 shmem[][CHUNK_K * K + SKEW_BF16];
|
||||
|
||||
// Warp and lane identification.
|
||||
const unsigned int warpId = threadIdx.x / WARP_SIZE;
|
||||
const unsigned int laneId = threadIdx.x % WARP_SIZE;
|
||||
|
||||
// Offset in shared memory from which the B matrix is stored.
|
||||
const size_t shmem_idx_b_off = BLOCK_COL_TILES * M;
|
||||
|
||||
// This pointer is used to access the C and D matrix tiles this warp computes.
|
||||
float *shmem_warp_tile_ptr = (float *)&shmem[0][0] + (warpId / BLOCK_ROW_WARPS) * SHMEM_STRIDE * N * BLOCK_ROW_WARPS
|
||||
+ (warpId % BLOCK_ROW_WARPS) * SHMEM_OFFSET;
|
||||
|
||||
// This pointer is used to stream the C and D matrices block-wide tile to and from shared memory.
|
||||
float *shmem_warp_stream_ptr = (float *)&shmem[0][0] + warpId * SHMEM_STRIDE * N;
|
||||
|
||||
// Adjust the beta scaler, as it'll be multiplied by alpha at the end of
|
||||
// each tile computation. Technically this is not generally correct (may result
|
||||
// in a loss of precision). Zero still needs to be specially handled though.
|
||||
beta /= alpha;
|
||||
|
||||
// Each CTA slides along the 128 x 128 tiles from the top left corner of the matrix to the
|
||||
// right and down, and selects the next tile to compute. Once there's no such tile,
|
||||
// all warps in this CTA exit.
|
||||
for (unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) {
|
||||
const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES);
|
||||
const unsigned int block_tile_j = (block_pos * BLOCK_COL_TILES) % N_TILES;
|
||||
|
||||
// Stop when there are no more D matrix tiles to compute in this CTA.
|
||||
if (block_tile_i >= M_TILES) {
|
||||
break;
|
||||
}
|
||||
|
||||
// This warp's pointer to the C matrix data to copy memory from to shared memory.
|
||||
const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N;
|
||||
const float *src_gmem_warp_stream_ptr = &C[gmem_idx];
|
||||
|
||||
// Stream multiple C tiles to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < N; i++) {
|
||||
*((int4 *)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId) =
|
||||
*((int4 *)(src_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// These fragments will accumulate the result of A and B matrix fragment multiplications
|
||||
// along the K_GLOBAL dimension.
|
||||
wmma::fragment<wmma::accumulator, M, N, K, float> c[WARP_COL_TILES][WARP_ROW_TILES];
|
||||
|
||||
// Load the C matrix tiles into fragments from shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
const float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * N + j * N;
|
||||
|
||||
wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Scale the C matrix.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < c[i][j].num_elements; t++) {
|
||||
c[i][j].x[t] *= beta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Select what warp copies what matrix to shared memory.
|
||||
// Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix.
|
||||
const __nv_bfloat16 *warp_ptr =
|
||||
(warpId < (WARPS_PER_BLOCK / 2))
|
||||
? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % (WARPS_PER_BLOCK / 2)) * 2)
|
||||
: (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % (WARPS_PER_BLOCK / 2)) * 2);
|
||||
|
||||
// Go through the global K dimension by a fixed step at a time.
|
||||
#pragma unroll
|
||||
for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) {
|
||||
// Copy slices of the A and B matrices to shared memory.
|
||||
// The first half of the warps in the CTA copy the A matrix, the rest copy the B matrix.
|
||||
size_t shmem_idx = warpId < (WARPS_PER_BLOCK / 2)
|
||||
? (M * (warpId % (WARPS_PER_BLOCK / 2)) * 2)
|
||||
: (N * (warpId % (WARPS_PER_BLOCK / 2)) * 2 + shmem_idx_b_off);
|
||||
|
||||
// First half of the warp copies the first row / column of the matrix,
|
||||
// the second half of the warp copies the next.
|
||||
const __nv_bfloat16 *lane_ptr = (warp_ptr + tile_k * K + (laneId / CHUNK_COPY_LINE_LANES) * K_GLOBAL);
|
||||
|
||||
// Shift the second half of the warp to the next row / column in the shared memory.
|
||||
shmem_idx += laneId / CHUNK_COPY_LINE_LANES;
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ((WARP_SIZE / 2) / CHUNK_COPY_LINES_PER_WARP) * 2; i++) {
|
||||
// Copy 16 bytes at once in each lane.
|
||||
*((int4 *)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES)) =
|
||||
*((int4 *)lane_ptr + (laneId % CHUNK_COPY_LINE_LANES));
|
||||
|
||||
// Advance the global memory pointer and the shared memory index.
|
||||
lane_ptr = lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP;
|
||||
shmem_idx += CHUNK_COPY_LINES_PER_WARP;
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Compute a grid of C matrix tiles in each warp.
|
||||
#pragma unroll
|
||||
for (int k_step = 0; k_step < CHUNK_K; k_step++) {
|
||||
wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a[WARP_COL_TILES];
|
||||
wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b[WARP_ROW_TILES];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
size_t shmem_idx_a = (warpId / BLOCK_ROW_WARPS) * M * BLOCK_ROW_WARPS + (i * M);
|
||||
const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_a][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_BF16);
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
if (i == 0) {
|
||||
// Load the B matrix fragment once, because it is going to be reused
|
||||
// against the other A matrix fragments.
|
||||
size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId % 2) + (j * N);
|
||||
const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_b][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_BF16);
|
||||
}
|
||||
|
||||
wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
// Store the D fragments to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
#pragma unroll
|
||||
// Uniform, point-wise transformations of ALL fragment elements by ALL threads in the
|
||||
// warp are well-defined even though element indices within fragment storage are not defined.
|
||||
for (int t = 0; t < c[i][j].num_elements; t++)
|
||||
c[i][j].x[t] *= alpha;
|
||||
|
||||
float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N;
|
||||
|
||||
wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Now that shared memory contains all the D tiles, stream them to global memory.
|
||||
float *dst_gmem_warp_stream_ptr = &D[gmem_idx];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < N; i++) {
|
||||
*((float4 *)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) =
|
||||
*((float4 *)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
__global__ void compute_bf16gemm_async_copy(const __nv_bfloat16 *A,
|
||||
const __nv_bfloat16 *B,
|
||||
const float *C,
|
||||
float *D,
|
||||
float alpha,
|
||||
float beta)
|
||||
{
|
||||
#if __CUDA_ARCH__ >= 800
|
||||
extern __shared__ __nv_bfloat16 shmem[][CHUNK_K * K + SKEW_BF16];
|
||||
|
||||
// Warp and lane identification.
|
||||
const unsigned int warpId = threadIdx.x / WARP_SIZE;
|
||||
const unsigned int laneId = threadIdx.x % WARP_SIZE;
|
||||
|
||||
// Offset in shared memory from which the B matrix is stored.
|
||||
constexpr size_t shmem_idx_b_off = BLOCK_COL_TILES * M;
|
||||
|
||||
// This pointer is used to access the C and D matrix tiles this warp computes.
|
||||
float *shmem_warp_tile_ptr = (float *)&shmem[0][0] + (warpId / BLOCK_ROW_WARPS) * SHMEM_STRIDE * N * BLOCK_ROW_WARPS
|
||||
+ (warpId % BLOCK_ROW_WARPS) * SHMEM_OFFSET;
|
||||
|
||||
// This pointer is used to stream the C and D matrices block-wide tile to and from shared memory.
|
||||
float *shmem_warp_stream_ptr = (float *)&shmem[0][0] + warpId * SHMEM_STRIDE * N;
|
||||
|
||||
// Adjust the beta scaler, as it'll be multiplied by alpha at the end of
|
||||
// each tile computation. Technically this is not generally correct (may result
|
||||
// in a loss of precision). Zero still needs to be specially handled though.
|
||||
beta /= alpha;
|
||||
|
||||
cuda::pipeline<cuda::thread_scope_thread> pipe = cuda::make_pipeline();
|
||||
const auto shape4 = cuda::aligned_size_t<alignof(float4)>(sizeof(float4));
|
||||
constexpr int loadStride = 2; // load 4 floats, left-shift by 2.
|
||||
|
||||
// Each CTA slides along the 128 x 128 tiles from the top left corner of the matrix to the
|
||||
// right and down, and selects the next tile to compute. Once there's no such tile,
|
||||
// all warps in this CTA exit.
|
||||
for (unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) {
|
||||
const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES);
|
||||
const unsigned int block_tile_j = (block_pos * BLOCK_COL_TILES) % N_TILES;
|
||||
|
||||
// Stop when there are no more D matrix tiles to compute in this CTA.
|
||||
if (block_tile_i >= M_TILES) {
|
||||
break;
|
||||
}
|
||||
|
||||
// This warp's pointer to the C matrix data to copy memory from to shared memory.
|
||||
const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N;
|
||||
const float *src_gmem_warp_stream_ptr = &C[gmem_idx];
|
||||
|
||||
// Stream multiple C tiles to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < N; i++) {
|
||||
pipe.producer_acquire();
|
||||
|
||||
cuda::memcpy_async(&shmem_warp_stream_ptr[(SHMEM_STRIDE * i) + (laneId << loadStride)],
|
||||
&src_gmem_warp_stream_ptr[(GLOBAL_MEM_STRIDE * i) + (laneId << loadStride)],
|
||||
shape4,
|
||||
pipe);
|
||||
|
||||
pipe.producer_commit();
|
||||
}
|
||||
|
||||
// Now wait for all the above issued 8 batches to complete.
|
||||
cuda::pipeline_consumer_wait_prior<0>(pipe);
|
||||
__syncthreads();
|
||||
|
||||
// These fragments will accumulate the result of A and B matrix fragment multiplications
|
||||
// along the K_GLOBAL dimension.
|
||||
wmma::fragment<wmma::accumulator, M, N, K, float> c[WARP_COL_TILES][WARP_ROW_TILES];
|
||||
|
||||
// Load the C matrix tiles into fragments from shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
const float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * N + j * N;
|
||||
|
||||
wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT);
|
||||
// Scale the C matrix.
|
||||
#pragma unroll
|
||||
for (int t = 0; t < c[i][j].num_elements; t++) {
|
||||
c[i][j].x[t] *= beta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pipe.consumer_release();
|
||||
|
||||
// sync here so that shared memory can then be used for loading A & B matrices.
|
||||
__syncthreads();
|
||||
// Select what warp copies what matrix to shared memory.
|
||||
// Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix.
|
||||
const __nv_bfloat16 *warp_ptr =
|
||||
(warpId < (WARPS_PER_BLOCK / 2))
|
||||
? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % (WARPS_PER_BLOCK / 2)) * 2)
|
||||
: (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % (WARPS_PER_BLOCK / 2)) * 2);
|
||||
|
||||
constexpr int chunksPerLane = ((WARP_SIZE / 2) / CHUNK_COPY_LINES_PER_WARP) * 2;
|
||||
constexpr int loadStrideBfloat8 = 3; // load 8 bfloats, left-shift by 3.
|
||||
const int laneLoadElem = (laneId % CHUNK_COPY_LINE_LANES) << loadStrideBfloat8;
|
||||
const int stridePerLaneCopy = (laneId / CHUNK_COPY_LINE_LANES);
|
||||
|
||||
// Go through the global K dimension by a fixed step at a time.
|
||||
#pragma unroll
|
||||
for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) {
|
||||
// Copy slices of the A and B matrices to shared memory.
|
||||
// The first half of the warps in the CTA copy the A matrix, the rest copy the B matrix.
|
||||
// As for bf16 MMA M == N we use M for warp 4-7 + shmem_idx_b_off.
|
||||
size_t shmem_idx =
|
||||
(M * (warpId % (WARPS_PER_BLOCK / 2)) * 2) + ((warpId / (WARPS_PER_BLOCK / 2)) * shmem_idx_b_off);
|
||||
|
||||
// First half of the warp copies the first row / column of the matrix,
|
||||
// the second half of the warp copies the next.
|
||||
const __nv_bfloat16 *lane_ptr = warp_ptr + tile_k * K + stridePerLaneCopy * K_GLOBAL + laneLoadElem;
|
||||
|
||||
// Shift the second half of the warp to the next row / column in the shared memory.
|
||||
shmem_idx += stridePerLaneCopy;
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < chunksPerLane; i++) {
|
||||
// Copy 16 bytes at once in each lane.
|
||||
pipe.producer_acquire();
|
||||
cuda::memcpy_async(&shmem[shmem_idx][laneLoadElem], lane_ptr, shape4, pipe);
|
||||
pipe.producer_commit();
|
||||
// Advance the global memory pointer and the shared memory index.
|
||||
lane_ptr = lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP;
|
||||
shmem_idx += CHUNK_COPY_LINES_PER_WARP;
|
||||
}
|
||||
cuda::pipeline_consumer_wait_prior<0>(pipe);
|
||||
__syncthreads();
|
||||
|
||||
// Compute a grid of C matrix tiles in each warp.
|
||||
#pragma unroll
|
||||
for (int k_step = 0; k_step < CHUNK_K; k_step++) {
|
||||
wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a[WARP_COL_TILES];
|
||||
wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b[WARP_ROW_TILES];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
size_t shmem_idx_a = (warpId / BLOCK_ROW_WARPS) * M * BLOCK_ROW_WARPS + (i * M);
|
||||
const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_a][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_BF16);
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
if (i == 0) {
|
||||
// Load the B matrix fragment once, because it is going to be reused
|
||||
// against the other A matrix fragments.
|
||||
size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId % 2) + (j * N);
|
||||
const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_b][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_BF16);
|
||||
}
|
||||
|
||||
wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pipe.consumer_release();
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
// Store the D fragments to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
#pragma unroll
|
||||
// Uniform, point-wise transformations of ALL fragment elements by ALL threads in the
|
||||
// warp are well-defined even though element indices within fragment storage are not defined.
|
||||
for (int t = 0; t < c[i][j].num_elements; t++)
|
||||
c[i][j].x[t] *= alpha;
|
||||
|
||||
float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N;
|
||||
|
||||
wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Now that shared memory contains all the D tiles, stream them to global memory.
|
||||
float *dst_gmem_warp_stream_ptr = &D[gmem_idx];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < N; i++) {
|
||||
*((int4 *)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) =
|
||||
*((int4 *)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// Performs an MxNxK bf16 GEMM (C=alpha*A*B + beta*C) assuming:
|
||||
// 1) Matrices are packed in memory.
|
||||
// 2) M, N and K are multiples of 16, 16 and 16 respectively.
|
||||
// 3) A is row major, B is column major matrix.
|
||||
// Note: This is a less performant version of the compute_bf16gemm kernel. It is designed for
|
||||
// demonstration purposes only to show the CUDA WMMA API use without relying on
|
||||
// availability of the shared memory.
|
||||
__global__ void simple_wmma_bf16gemm(__nv_bfloat16 *a,
|
||||
__nv_bfloat16 *b,
|
||||
float *c,
|
||||
float *d,
|
||||
int m_ld,
|
||||
int n_ld,
|
||||
int k_ld,
|
||||
float alpha,
|
||||
float beta)
|
||||
{
|
||||
#if __CUDA_ARCH__ >= 800
|
||||
// Leading dimensions. Packed with no transpositions.
|
||||
int lda = k_ld;
|
||||
int ldb = k_ld;
|
||||
int ldc = n_ld;
|
||||
|
||||
// Tile using a 2D grid
|
||||
int warpM = (blockIdx.x * blockDim.x + threadIdx.x) / warpSize;
|
||||
int warpN = (blockIdx.y * blockDim.y + threadIdx.y);
|
||||
|
||||
// Declare the fragments
|
||||
wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a_frag;
|
||||
wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b_frag;
|
||||
wmma::fragment<wmma::accumulator, M, N, K, float> acc_frag;
|
||||
wmma::fragment<wmma::accumulator, M, N, K, float> c_frag;
|
||||
|
||||
wmma::fill_fragment(acc_frag, 0.0f);
|
||||
|
||||
// Loop over k
|
||||
for (int i = 0; i < k_ld; i += K) {
|
||||
int aCol = i;
|
||||
int aRow = warpM * M;
|
||||
|
||||
int bCol = i;
|
||||
int bRow = warpN * N;
|
||||
|
||||
// Bounds checking
|
||||
if (aRow < m_ld && aCol < k_ld && bRow < k_ld && bCol < n_ld) {
|
||||
// Load the inputs
|
||||
wmma::load_matrix_sync(a_frag, a + aCol + aRow * lda, lda);
|
||||
wmma::load_matrix_sync(b_frag, b + bRow + bCol * ldb, ldb);
|
||||
|
||||
// Perform the matrix multiplication
|
||||
wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag);
|
||||
}
|
||||
}
|
||||
|
||||
// Load in the current value of c, scale it by beta, and add this our result scaled by alpha
|
||||
int cCol = warpN * N;
|
||||
int cRow = warpM * M;
|
||||
|
||||
if (cRow < m_ld && cCol < n_ld) {
|
||||
wmma::load_matrix_sync(c_frag, c + cCol + cRow * ldc, ldc, wmma::mem_row_major);
|
||||
|
||||
for (int i = 0; i < c_frag.num_elements; i++) {
|
||||
c_frag.x[i] = alpha * acc_frag.x[i] + beta * c_frag.x[i];
|
||||
}
|
||||
|
||||
// Store the output
|
||||
wmma::store_matrix_sync(d + cCol + cRow * ldc, c_frag, ldc, wmma::mem_row_major);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
__host__ void matMultiplyOnHost(__nv_bfloat16 *A,
|
||||
__nv_bfloat16 *B,
|
||||
float *C,
|
||||
float alpha,
|
||||
float beta,
|
||||
int numARows,
|
||||
int numAColumns,
|
||||
int numBRows,
|
||||
int numBColumns,
|
||||
int numCRows,
|
||||
int numCColumns)
|
||||
{
|
||||
for (int i = 0; i < numCRows; i++) {
|
||||
for (int j = 0; j < numCColumns; j++) {
|
||||
float temp = 0.0;
|
||||
|
||||
for (int k = 0; k < numAColumns; k++) {
|
||||
temp += (float)A[i * numAColumns + k] * (float)B[j * numBRows + k];
|
||||
}
|
||||
|
||||
C[i * numCColumns + j] = temp * alpha + beta * C[i * numCColumns + j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
printf("Initializing...\n");
|
||||
|
||||
int dev = findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
cudaDeviceProp deviceProp;
|
||||
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, dev));
|
||||
|
||||
// Tensor cores require a GPU of Volta (SM8X) architecture or higher.
|
||||
if (deviceProp.major < 8) {
|
||||
printf("bf16TensorCoreGemm requires requires SM 8.0 or higher to use Tensor Cores. Exiting...\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
printf("M: %d (%d x %d)\n", M_GLOBAL, M, M_TILES);
|
||||
printf("N: %d (%d x %d)\n", N_GLOBAL, N, N_TILES);
|
||||
printf("K: %d (%d x %d)\n", K_GLOBAL, K, K_TILES);
|
||||
|
||||
__nv_bfloat16 *A_h = NULL;
|
||||
__nv_bfloat16 *B_h = NULL;
|
||||
float *C_h = NULL;
|
||||
#if CPU_DEBUG
|
||||
float *result_hD = NULL;
|
||||
float *result_host = NULL;
|
||||
#endif
|
||||
|
||||
A_h = (__nv_bfloat16 *)malloc(sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL);
|
||||
B_h = (__nv_bfloat16 *)malloc(sizeof(__nv_bfloat16) * K_GLOBAL * N_GLOBAL);
|
||||
C_h = (float *)malloc(sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
#if CPU_DEBUG
|
||||
result_hD = (float *)malloc(sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
result_host = (float *)malloc(sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
#endif
|
||||
|
||||
__nv_bfloat16 *A = NULL;
|
||||
__nv_bfloat16 *B = NULL;
|
||||
float *C = NULL;
|
||||
float *D = NULL;
|
||||
|
||||
checkCudaErrors(cudaMalloc((void **)&A, sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc((void **)&B, sizeof(__nv_bfloat16) * N_GLOBAL * K_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc((void **)&C, sizeof(float) * M_GLOBAL * N_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc((void **)&D, sizeof(float) * M_GLOBAL * N_GLOBAL));
|
||||
|
||||
assert(((unsigned long long)A) % 128 == 0);
|
||||
assert(((unsigned long long)B) % 128 == 0);
|
||||
assert(((unsigned long long)C) % 128 == 0);
|
||||
assert(((unsigned long long)D) % 128 == 0);
|
||||
|
||||
init_host_matrices(A_h, B_h, C_h);
|
||||
|
||||
printf("Preparing data for GPU...\n");
|
||||
|
||||
checkCudaErrors(cudaMemcpy(A, A_h, sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(B, B_h, sizeof(__nv_bfloat16) * N_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(C, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemset(D, 0, sizeof(float) * M_GLOBAL * N_GLOBAL));
|
||||
|
||||
enum {
|
||||
// Compute the right amount of shared memory to request.
|
||||
// We need shared memory to hold per-CTA C and D matrix tiles, and to cache per-CTA chunks
|
||||
// of the A and B matrices. Therefore, the right amount to request is the maximum of those
|
||||
// two numbers.
|
||||
SHMEM_SZ = MAX(sizeof(__nv_bfloat16) * (BLOCK_COL_TILES * M) * (CHUNK_K * K + SKEW_BF16) * 2,
|
||||
M * (BLOCK_ROW_WARPS * WARP_ROW_TILES) * N * (BLOCK_COL_WARPS * WARP_COL_TILES) * sizeof(float))
|
||||
};
|
||||
|
||||
printf("Required shared memory size: %lu Kb\n", SHMEM_SZ / 1024UL);
|
||||
|
||||
const float alpha = 1.1f;
|
||||
const float beta = 1.2f;
|
||||
|
||||
cudaEvent_t start, stop;
|
||||
|
||||
checkCudaErrors(cudaEventCreate(&start));
|
||||
checkCudaErrors(cudaEventCreate(&stop));
|
||||
checkCudaErrors(cudaEventRecord(start));
|
||||
|
||||
// kernel to run - default (b16mma_shmem_gemm_async_copy == 0)
|
||||
kernels selected_kernel = bf16mma_shmem_gemm_async_copy;
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "kernel")) {
|
||||
int kernel_number = getCmdLineArgumentInt(argc, (const char **)argv, "kernel");
|
||||
if (kernel_number < 3) {
|
||||
selected_kernel = (kernels)kernel_number;
|
||||
}
|
||||
else {
|
||||
printf("Error: kernel number should be between 0 to 2, you have entered %d\n", kernel_number);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
// If enough shared memory available on the GPU use high performant kernel
|
||||
if ((deviceProp.sharedMemPerMultiprocessor >= SHMEM_SZ) && (selected_kernel != simple_bf16mma_gemm)) {
|
||||
printf("Computing using high performance kernel = %d - %s\n", selected_kernel, kernelNames[selected_kernel]);
|
||||
|
||||
switch (selected_kernel) {
|
||||
case bf16mma_shmem_gemm_async_copy:
|
||||
default:
|
||||
checkCudaErrors(cudaFuncSetAttribute(
|
||||
compute_bf16gemm_async_copy, cudaFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ));
|
||||
checkKernelErrors(
|
||||
(compute_bf16gemm_async_copy<<<deviceProp.multiProcessorCount * 2, THREADS_PER_BLOCK, SHMEM_SZ>>>(
|
||||
A, B, C, D, alpha, beta)));
|
||||
break;
|
||||
case bf16mma_shmem_gemm:
|
||||
checkCudaErrors(
|
||||
cudaFuncSetAttribute(compute_bf16gemm, cudaFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ));
|
||||
checkKernelErrors((compute_bf16gemm<<<deviceProp.multiProcessorCount * 2, THREADS_PER_BLOCK, SHMEM_SZ>>>(
|
||||
A, B, C, D, alpha, beta)));
|
||||
break;
|
||||
}
|
||||
#if CPU_DEBUG
|
||||
checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyDeviceToHost));
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
dim3 gridDim;
|
||||
dim3 blockDim;
|
||||
|
||||
// blockDim.x must be a multple of warpSize
|
||||
// 128x4 means we have 16 warps and a block computes a 64x64 output tile
|
||||
blockDim.x = 128;
|
||||
blockDim.y = 4;
|
||||
|
||||
gridDim.x = (M_GLOBAL + (M * blockDim.x / 32 - 1)) / (M * blockDim.x / 32);
|
||||
gridDim.y = (N_GLOBAL + N * blockDim.y - 1) / (N * blockDim.y);
|
||||
|
||||
printf("Computing... using simple_wmma_gemm kernel\n");
|
||||
simple_wmma_bf16gemm<<<gridDim, blockDim>>>(A, B, C, D, M_GLOBAL, N_GLOBAL, K_GLOBAL, alpha, beta);
|
||||
#if CPU_DEBUG
|
||||
checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyDeviceToHost));
|
||||
#endif
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaEventRecord(stop));
|
||||
checkCudaErrors(cudaEventSynchronize(stop));
|
||||
|
||||
#if CPU_DEBUG
|
||||
printf("Verifying correctness of the computations...\n");
|
||||
|
||||
memcpy(result_host, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
|
||||
matMultiplyOnHost(A_h, B_h, result_host, alpha, beta, M_GLOBAL, K_GLOBAL, K_GLOBAL, N_GLOBAL, M_GLOBAL, N_GLOBAL);
|
||||
|
||||
for (int i = 0; i < N_GLOBAL * M_GLOBAL; i++) {
|
||||
if (fabs(result_hD[i] - result_host[i]) > 0.1f) {
|
||||
printf("mismatch i=%d result_hD=%f result_host=%f\n", i, result_hD[i], result_host[i]);
|
||||
}
|
||||
}
|
||||
free(result_hD);
|
||||
free(result_host);
|
||||
#endif
|
||||
|
||||
float milliseconds = 0;
|
||||
|
||||
checkCudaErrors(cudaEventElapsedTime(&milliseconds, start, stop));
|
||||
|
||||
printf("Time: %f ms\n", milliseconds);
|
||||
printf("TFLOPS: %.2f\n", (((double)M_GLOBAL * N_GLOBAL * K_GLOBAL * 2) / (milliseconds / 1000.)) / 1e12);
|
||||
|
||||
free(A_h);
|
||||
free(B_h);
|
||||
free(C_h);
|
||||
checkCudaErrors(cudaFree((void *)A));
|
||||
checkCudaErrors(cudaFree((void *)B));
|
||||
checkCudaErrors(cudaFree((void *)C));
|
||||
checkCudaErrors(cudaFree((void *)D));
|
||||
|
||||
return 0;
|
||||
}
|
||||
18
cpp/3_CUDA_Features/binaryPartitionCG/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/binaryPartitionCG/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/binaryPartitionCG/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/binaryPartitionCG/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
34
cpp/3_CUDA_Features/binaryPartitionCG/CMakeLists.txt
Normal file
34
cpp/3_CUDA_Features/binaryPartitionCG/CMakeLists.txt
Normal file
@@ -0,0 +1,34 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(binaryPartitionCG LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for binaryPartitionCG
|
||||
add_executable(binaryPartitionCG binaryPartitionCG.cu)
|
||||
|
||||
target_compile_options(binaryPartitionCG PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(binaryPartitionCG PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(binaryPartitionCG PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
32
cpp/3_CUDA_Features/binaryPartitionCG/README.md
Normal file
32
cpp/3_CUDA_Features/binaryPartitionCG/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# binaryPartitionCG - Binary Partition Cooperative Groups
|
||||
|
||||
## Description
|
||||
|
||||
This sample is a simple code that illustrates binary partition cooperative groups and reduce within the thread block.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Cooperative Groups
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 5.0 ](https://developer.nvidia.com/cuda-gpus) [SM 5.2 ](https://developer.nvidia.com/cuda-gpus) [SM 5.3 ](https://developer.nvidia.com/cuda-gpus) [SM 6.0 ](https://developer.nvidia.com/cuda-gpus) [SM 6.1 ](https://developer.nvidia.com/cuda-gpus) [SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaStreamCreateWithFlags, cudaFree, cudaMallocHost, cudaFreeHost, cudaStreamSynchronize, cudaMalloc, cudaMemsetAsync, cudaMemcpyAsync, cudaOccupancyMaxPotentialBlockSize
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
|
||||
## References (for more details)
|
||||
158
cpp/3_CUDA_Features/binaryPartitionCG/binaryPartitionCG.cu
Normal file
158
cpp/3_CUDA_Features/binaryPartitionCG/binaryPartitionCG.cu
Normal file
@@ -0,0 +1,158 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This sample illustrates basic usage of binary partition cooperative groups
|
||||
* within the thread block tile when divergent path exists.
|
||||
* 1.) Each thread loads a value from random array.
|
||||
* 2.) then checks if it is odd or even.
|
||||
* 3.) create binary partition group based on the above predicate
|
||||
* 4.) we count the number of odd/even in the group based on size of the binary
|
||||
groups
|
||||
* 5.) write it global counter of odd.
|
||||
* 6.) sum the values loaded by individual threads(using reduce) and write it to
|
||||
global even & odd elements sum.
|
||||
*
|
||||
* **NOTE** :
|
||||
* binary_partition results in splitting warp into divergent thread groups
|
||||
* this is not good from performance perspective, but in cases where warp
|
||||
* divergence is inevitable one can use binary_partition group.
|
||||
*/
|
||||
|
||||
#include <cooperative_groups.h>
|
||||
#include <cooperative_groups/reduce.h>
|
||||
#include <helper_cuda.h>
|
||||
#include <stdio.h>
|
||||
|
||||
namespace cg = cooperative_groups;
|
||||
|
||||
void initOddEvenArr(int *inputArr, unsigned int size)
|
||||
{
|
||||
for (int i = 0; i < size; i++) {
|
||||
inputArr[i] = rand() % 50;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CUDA kernel device code
|
||||
*
|
||||
* Creates cooperative groups and performs odd/even counting & summation.
|
||||
*/
|
||||
__global__ void oddEvenCountAndSumCG(int *inputArr, int *numOfOdds, int *sumOfOddAndEvens, unsigned int size)
|
||||
{
|
||||
cg::thread_block cta = cg::this_thread_block();
|
||||
cg::grid_group grid = cg::this_grid();
|
||||
cg::thread_block_tile<32> tile32 = cg::tiled_partition<32>(cta);
|
||||
|
||||
for (int i = grid.thread_rank(); i < size; i += grid.size()) {
|
||||
int elem = inputArr[i];
|
||||
auto subTile = cg::binary_partition(tile32, elem & 1);
|
||||
if (elem & 1) // Odd numbers group
|
||||
{
|
||||
int oddGroupSum = cg::reduce(subTile, elem, cg::plus<int>());
|
||||
|
||||
if (subTile.thread_rank() == 0) {
|
||||
// Add number of odds present in this group of Odds.
|
||||
atomicAdd(numOfOdds, subTile.size());
|
||||
|
||||
// Add local reduction of odds present in this group of Odds.
|
||||
atomicAdd(&sumOfOddAndEvens[0], oddGroupSum);
|
||||
}
|
||||
}
|
||||
else // Even numbers group
|
||||
{
|
||||
int evenGroupSum = cg::reduce(subTile, elem, cg::plus<int>());
|
||||
|
||||
if (subTile.thread_rank() == 0) {
|
||||
// Add local reduction of even present in this group of evens.
|
||||
atomicAdd(&sumOfOddAndEvens[1], evenGroupSum);
|
||||
}
|
||||
}
|
||||
// reconverge warp so for next loop iteration we ensure convergence of
|
||||
// above diverged threads to perform coalesced loads of inputArr.
|
||||
cg::sync(tile32);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Host main routine
|
||||
*/
|
||||
int main(int argc, const char **argv)
|
||||
{
|
||||
int deviceId = findCudaDevice(argc, argv);
|
||||
int *h_inputArr, *d_inputArr;
|
||||
int *h_numOfOdds, *d_numOfOdds;
|
||||
int *h_sumOfOddEvenElems, *d_sumOfOddEvenElems;
|
||||
unsigned int arrSize = 1024 * 100;
|
||||
|
||||
checkCudaErrors(cudaMallocHost(&h_inputArr, sizeof(int) * arrSize));
|
||||
checkCudaErrors(cudaMallocHost(&h_numOfOdds, sizeof(int)));
|
||||
checkCudaErrors(cudaMallocHost(&h_sumOfOddEvenElems, sizeof(int) * 2));
|
||||
initOddEvenArr(h_inputArr, arrSize);
|
||||
|
||||
cudaStream_t stream;
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
|
||||
checkCudaErrors(cudaMalloc(&d_inputArr, sizeof(int) * arrSize));
|
||||
checkCudaErrors(cudaMalloc(&d_numOfOdds, sizeof(int)));
|
||||
checkCudaErrors(cudaMalloc(&d_sumOfOddEvenElems, sizeof(int) * 2));
|
||||
|
||||
checkCudaErrors(cudaMemcpyAsync(d_inputArr, h_inputArr, sizeof(int) * arrSize, cudaMemcpyHostToDevice, stream));
|
||||
checkCudaErrors(cudaMemsetAsync(d_numOfOdds, 0, sizeof(int), stream));
|
||||
checkCudaErrors(cudaMemsetAsync(d_sumOfOddEvenElems, 0, 2 * sizeof(int), stream));
|
||||
|
||||
// Launch the kernel
|
||||
int threadsPerBlock = 0;
|
||||
int blocksPerGrid = 0;
|
||||
checkCudaErrors(cudaOccupancyMaxPotentialBlockSize(&blocksPerGrid, &threadsPerBlock, oddEvenCountAndSumCG, 0, 0));
|
||||
|
||||
printf("\nLaunching %d blocks with %d threads...\n\n", blocksPerGrid, threadsPerBlock);
|
||||
|
||||
oddEvenCountAndSumCG<<<blocksPerGrid, threadsPerBlock, 0, stream>>>(
|
||||
d_inputArr, d_numOfOdds, d_sumOfOddEvenElems, arrSize);
|
||||
|
||||
checkCudaErrors(cudaMemcpyAsync(h_numOfOdds, d_numOfOdds, sizeof(int), cudaMemcpyDeviceToHost, stream));
|
||||
checkCudaErrors(
|
||||
cudaMemcpyAsync(h_sumOfOddEvenElems, d_sumOfOddEvenElems, 2 * sizeof(int), cudaMemcpyDeviceToHost, stream));
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
|
||||
printf("Array size = %d Num of Odds = %d Sum of Odds = %d Sum of Evens %d\n",
|
||||
arrSize,
|
||||
h_numOfOdds[0],
|
||||
h_sumOfOddEvenElems[0],
|
||||
h_sumOfOddEvenElems[1]);
|
||||
printf("\n...Done.\n\n");
|
||||
|
||||
checkCudaErrors(cudaFreeHost(h_inputArr));
|
||||
checkCudaErrors(cudaFreeHost(h_numOfOdds));
|
||||
checkCudaErrors(cudaFreeHost(h_sumOfOddEvenElems));
|
||||
|
||||
checkCudaErrors(cudaFree(d_inputArr));
|
||||
checkCudaErrors(cudaFree(d_numOfOdds));
|
||||
checkCudaErrors(cudaFree(d_sumOfOddEvenElems));
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
18
cpp/3_CUDA_Features/bindlessTexture/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/bindlessTexture/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/bindlessTexture/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/bindlessTexture/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
96
cpp/3_CUDA_Features/bindlessTexture/CMakeLists.txt
Normal file
96
cpp/3_CUDA_Features/bindlessTexture/CMakeLists.txt
Normal file
@@ -0,0 +1,96 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(bindlessTexture LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
if(WIN32)
|
||||
set(PC_GLUT_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/../../../Common")
|
||||
set(PC_GLUT_LIBRARY_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/../../../Common/lib/x64")
|
||||
# The GLEW library built on Windows on Arm system is named as glew32.lib/glew32.dll by default.
|
||||
if(EXISTS "${PC_GLUT_LIBRARY_DIRS}/glew32.lib")
|
||||
set(GLEW_LIB_NAME "glew32")
|
||||
else()
|
||||
set(GLEW_LIB_NAME "glew64")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
find_package(OpenGL)
|
||||
find_package(GLUT)
|
||||
|
||||
# Source file
|
||||
if(${OpenGL_FOUND})
|
||||
if (${GLUT_FOUND})
|
||||
# Add target for bindlessTexture
|
||||
add_executable(bindlessTexture bindlessTexture.cpp bindlessTexture_kernel.cu)
|
||||
|
||||
target_compile_options(bindlessTexture PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(bindlessTexture PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(bindlessTexture PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
target_include_directories(bindlessTexture PUBLIC
|
||||
${OPENGL_INCLUDE_DIR}
|
||||
${CUDAToolkit_INCLUDE_DIRS}
|
||||
${GLUT_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
target_link_libraries(bindlessTexture
|
||||
${OPENGL_LIBRARIES}
|
||||
${GLUT_LIBRARIES}
|
||||
)
|
||||
|
||||
# Copy clock_kernel.cu to the output directory
|
||||
add_custom_command(TARGET bindlessTexture POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/data
|
||||
${CMAKE_CURRENT_BINARY_DIR}/data
|
||||
)
|
||||
|
||||
if(WIN32)
|
||||
target_link_libraries(bindlessTexture
|
||||
${PC_GLUT_LIBRARY_DIRS}/freeglut.lib
|
||||
${PC_GLUT_LIBRARY_DIRS}/${GLEW_LIB_NAME}.lib
|
||||
)
|
||||
|
||||
add_custom_command(TARGET bindlessTexture
|
||||
POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../../bin/win64/$<CONFIGURATION>/freeglut.dll
|
||||
${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>
|
||||
)
|
||||
|
||||
add_custom_command(TARGET bindlessTexture
|
||||
POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../../bin/win64/$<CONFIGURATION>/${GLEW_LIB_NAME}.dll
|
||||
${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>
|
||||
)
|
||||
endif()
|
||||
|
||||
else()
|
||||
message(STATUS "GLUT not found - will not build sample 'bindlessTexture'")
|
||||
endif()
|
||||
else()
|
||||
message(STATUS "OpenGL not found - will not build sample 'bindlessTexture'")
|
||||
endif()
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
34
cpp/3_CUDA_Features/bindlessTexture/README.md
Normal file
34
cpp/3_CUDA_Features/bindlessTexture/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# bindlessTexture - Bindless Texture
|
||||
|
||||
## Description
|
||||
|
||||
This example demonstrates use of cudaSurfaceObject, cudaTextureObject, and MipMap support in CUDA. A GPU with Compute Capability SM 3.0 is required to run the sample.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Graphics Interop, Texture
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaGetMipmappedArrayLevel, cudaGraphicsMapResources, cudaDestroySurfaceObject, cudaExtent, cudaDeviceSynchronize, cudaCreateSurfaceObject, cudaMallocMipmappedArray, cudaPitchedPtr, cudaGraphicsResourceGetMappedPointer, cudaCreateTextureObject, cudaGraphicsUnmapResources, cudaMallocArray, cudaFreeArray, cudaArrayGetInfo, cudaGetLastError, cudaDestroyTextureObject, cudaGraphicsGLRegisterBuffer, cudaFreeMipmappedArray, cudaFree, cudaGraphicsUnregisterResource, cudaMalloc
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[X11](../../../README.md#x11), [OpenGL](../../../README.md#opengl), [Freeglut](../../../README.md#freeglut), [GLEW](../../../README.md#glew)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
420
cpp/3_CUDA_Features/bindlessTexture/bindlessTexture.cpp
Normal file
420
cpp/3_CUDA_Features/bindlessTexture/bindlessTexture.cpp
Normal file
@@ -0,0 +1,420 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/*
|
||||
Bindless Texture/Surface
|
||||
|
||||
This sample generates a few 2D textures and uses cudaTextureObjects to
|
||||
perform pseudo virtual texturing for display. One 2D texture stores
|
||||
references to other textures.
|
||||
Furthermore use of mip mapping is shown using both cudaTextureObjects
|
||||
and cudaSurfaceObjects.
|
||||
|
||||
Look into the bindlessTexture_kernel.cu file for most relevant code.
|
||||
*/
|
||||
|
||||
#include <helper_gl.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <vector>
|
||||
#if defined(__APPLE__) || defined(MACOSX)
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
#include <GLUT/glut.h>
|
||||
#ifndef glutCloseFunc
|
||||
#define glutCloseFunc glutWMCloseFunc
|
||||
#endif
|
||||
#else
|
||||
#include <GL/freeglut.h>
|
||||
#endif
|
||||
|
||||
#include <cuda_gl_interop.h>
|
||||
#include <helper_functions.h>
|
||||
|
||||
#include "bindlessTexture.h"
|
||||
|
||||
#define MAX_EPSILON_ERROR 5.0f
|
||||
#define THRESHOLD 0.15f
|
||||
|
||||
const char *sSDKsample = "CUDA bindlessTexture";
|
||||
|
||||
const char *imageFilenames[] = {
|
||||
"flower.ppm",
|
||||
"person.ppm",
|
||||
"sponge.ppm",
|
||||
};
|
||||
|
||||
const cudaExtent atlasSize = make_cudaExtent(4, 4, 0);
|
||||
const dim3 windowSize(512, 512);
|
||||
const dim3 windowBlockSize(16, 16, 1);
|
||||
const dim3 windowGridSize(windowSize.x / windowBlockSize.x, windowSize.y / windowBlockSize.y);
|
||||
|
||||
float lod = 0.5; // texture mip map level
|
||||
|
||||
GLuint pbo; // OpenGL pixel buffer object
|
||||
struct cudaGraphicsResource *cuda_pbo_resource = NULL; // CUDA Graphics Resource (to transfer PBO)
|
||||
|
||||
bool animate = true;
|
||||
|
||||
StopWatchInterface *timer = NULL;
|
||||
|
||||
uint *d_output = NULL;
|
||||
|
||||
// Auto-Verification Code
|
||||
const int frameCheckNumber = 4;
|
||||
int fpsCount = 0; // FPS count for averaging
|
||||
int fpsLimit = 1; // FPS limit for sampling
|
||||
int g_Index = 0;
|
||||
unsigned int frameCount = 0;
|
||||
unsigned int g_TotalErrors = 0;
|
||||
|
||||
int *pArgc = NULL;
|
||||
char **pArgv = NULL;
|
||||
|
||||
extern "C" void initAtlasAndImages(const Image *images, size_t numImages, cudaExtent atlasSize);
|
||||
extern "C" void deinitAtlasAndImages();
|
||||
extern "C" void randomizeAtlas();
|
||||
extern "C" void renderAtlasImage(dim3 gridSize, dim3 blockSize, uint *d_output, uint imageW, uint imageH, float lod);
|
||||
|
||||
void computeFPS()
|
||||
{
|
||||
frameCount++;
|
||||
fpsCount++;
|
||||
|
||||
if (fpsCount == fpsLimit) {
|
||||
char fps[256];
|
||||
float ifps = 1.f / (sdkGetAverageTimerValue(&timer) / 1000.f);
|
||||
sprintf(fps, "%s: %3.1f fps", sSDKsample, ifps);
|
||||
|
||||
glutSetWindowTitle(fps);
|
||||
fpsCount = 0;
|
||||
|
||||
fpsLimit = (int)MAX(1.0f, ifps);
|
||||
sdkResetTimer(&timer);
|
||||
}
|
||||
}
|
||||
|
||||
// render image using CUDA
|
||||
void render()
|
||||
{
|
||||
// map PBO to get CUDA device pointer
|
||||
checkCudaErrors(cudaGraphicsMapResources(1, &cuda_pbo_resource, 0));
|
||||
size_t num_bytes;
|
||||
checkCudaErrors(cudaGraphicsResourceGetMappedPointer((void **)&d_output, &num_bytes, cuda_pbo_resource));
|
||||
|
||||
// call CUDA kernel, writing results to PBO
|
||||
renderAtlasImage(windowGridSize, windowBlockSize, d_output, windowSize.x, windowSize.y, lod);
|
||||
|
||||
getLastCudaError("render_kernel failed");
|
||||
|
||||
checkCudaErrors(cudaGraphicsUnmapResources(1, &cuda_pbo_resource, 0));
|
||||
}
|
||||
|
||||
// display results using OpenGL (called by GLUT)
|
||||
void display()
|
||||
{
|
||||
sdkStartTimer(&timer);
|
||||
|
||||
render();
|
||||
|
||||
// display results
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
|
||||
// draw image from PBO
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glRasterPos2i(0, 0);
|
||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
|
||||
glDrawPixels(windowSize.x, windowSize.y, GL_RGBA, GL_UNSIGNED_BYTE, 0);
|
||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
|
||||
|
||||
glutSwapBuffers();
|
||||
glutReportErrors();
|
||||
|
||||
sdkStopTimer(&timer);
|
||||
computeFPS();
|
||||
}
|
||||
|
||||
void idle()
|
||||
{
|
||||
if (animate) {
|
||||
lod += 0.02f;
|
||||
glutPostRedisplay();
|
||||
}
|
||||
}
|
||||
|
||||
void keyboard(unsigned char key, int x, int y)
|
||||
{
|
||||
switch (key) {
|
||||
case 27:
|
||||
#if defined(__APPLE__) || defined(MACOSX)
|
||||
exit(EXIT_SUCCESS);
|
||||
#else
|
||||
glutDestroyWindow(glutGetWindow());
|
||||
return;
|
||||
#endif
|
||||
break;
|
||||
|
||||
case '=':
|
||||
case '+':
|
||||
lod += 0.25f;
|
||||
break;
|
||||
|
||||
case '-':
|
||||
lod -= 0.25f;
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
randomizeAtlas();
|
||||
break;
|
||||
|
||||
case ' ':
|
||||
animate = !animate;
|
||||
lod = 0.0f;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
glutPostRedisplay();
|
||||
}
|
||||
|
||||
void reshape(int x, int y)
|
||||
{
|
||||
glViewport(0, 0, x, y);
|
||||
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glLoadIdentity();
|
||||
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glLoadIdentity();
|
||||
glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
// Global cleanup function
|
||||
// Shared by both GL and non-GL code paths
|
||||
void cleanup()
|
||||
{
|
||||
sdkDeleteTimer(&timer);
|
||||
|
||||
// unregister this buffer object from CUDA C
|
||||
if (cuda_pbo_resource) {
|
||||
cudaGraphicsUnregisterResource(cuda_pbo_resource);
|
||||
glDeleteBuffers(1, &pbo);
|
||||
}
|
||||
}
|
||||
|
||||
void cleanup_all()
|
||||
{
|
||||
cleanup();
|
||||
deinitAtlasAndImages();
|
||||
}
|
||||
|
||||
void initGLBuffers()
|
||||
{
|
||||
// create pixel buffer object
|
||||
glGenBuffers(1, &pbo);
|
||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
|
||||
glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, windowSize.x * windowSize.y * sizeof(GLubyte) * 4, 0, GL_STREAM_DRAW_ARB);
|
||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
|
||||
|
||||
// register this buffer object with CUDA
|
||||
checkCudaErrors(cudaGraphicsGLRegisterBuffer(&cuda_pbo_resource, pbo, cudaGraphicsMapFlagsWriteDiscard));
|
||||
}
|
||||
|
||||
// Load raw data from disk
|
||||
uchar *loadRawFile(const char *filename, size_t size)
|
||||
{
|
||||
FILE *fp = fopen(filename, "rb");
|
||||
|
||||
if (!fp) {
|
||||
fprintf(stderr, "Error opening file '%s'\n", filename);
|
||||
return 0;
|
||||
}
|
||||
|
||||
uchar *data = (uchar *)malloc(size);
|
||||
size_t read = fread(data, 1, size, fp);
|
||||
fclose(fp);
|
||||
|
||||
printf("Read '%s', %zu bytes\n", filename, read);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
void initGL(int *argc, char **argv)
|
||||
{
|
||||
// initialize GLUT callback functions
|
||||
glutInit(argc, argv);
|
||||
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
|
||||
glutInitWindowSize(windowSize.x, windowSize.y);
|
||||
glutCreateWindow(sSDKsample);
|
||||
glutDisplayFunc(display);
|
||||
glutKeyboardFunc(keyboard);
|
||||
glutReshapeFunc(reshape);
|
||||
glutIdleFunc(idle);
|
||||
|
||||
if (!isGLVersionSupported(2, 0) || !areGLExtensionsSupported("GL_ARB_pixel_buffer_object")) {
|
||||
fprintf(stderr, "Required OpenGL extensions are missing.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
void runAutoTest(const char *ref_file, char *exec_path)
|
||||
{
|
||||
size_t windowBytes = windowSize.x * windowSize.y * sizeof(GLubyte) * 4;
|
||||
|
||||
checkCudaErrors(cudaMalloc((void **)&d_output, windowBytes));
|
||||
|
||||
// render the volumeData
|
||||
renderAtlasImage(windowGridSize, windowBlockSize, d_output, windowSize.x, windowSize.y, lod);
|
||||
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
getLastCudaError("render_kernel failed");
|
||||
|
||||
void *h_output = malloc(windowBytes);
|
||||
checkCudaErrors(cudaMemcpy(h_output, d_output, windowBytes, cudaMemcpyDeviceToHost));
|
||||
sdkDumpBin(h_output, (unsigned int)windowBytes, "bindlessTexture.bin");
|
||||
|
||||
bool bTestResult = sdkCompareBin2BinFloat("bindlessTexture.bin",
|
||||
sdkFindFilePath(ref_file, exec_path),
|
||||
windowSize.x * windowSize.y,
|
||||
MAX_EPSILON_ERROR,
|
||||
THRESHOLD,
|
||||
exec_path);
|
||||
|
||||
checkCudaErrors(cudaFree(d_output));
|
||||
free(h_output);
|
||||
deinitAtlasAndImages();
|
||||
|
||||
sdkStopTimer(&timer);
|
||||
sdkDeleteTimer(&timer);
|
||||
|
||||
exit(bTestResult ? EXIT_SUCCESS : EXIT_FAILURE);
|
||||
}
|
||||
|
||||
void loadImageData(const char *exe_path)
|
||||
{
|
||||
std::vector<Image> images;
|
||||
|
||||
for (size_t i = 0; i < sizeof(imageFilenames) / sizeof(imageFilenames[0]); i++) {
|
||||
unsigned int imgWidth = 0;
|
||||
unsigned int imgHeight = 0;
|
||||
uchar *imgData = NULL;
|
||||
const char *imgPath = 0;
|
||||
const char *imgFilename = imageFilenames[i];
|
||||
|
||||
if (exe_path) {
|
||||
imgPath = sdkFindFilePath(imgFilename, exe_path);
|
||||
}
|
||||
|
||||
if (imgPath == 0) {
|
||||
printf("Error finding image file '%s'\n", imgFilename);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
sdkLoadPPM4(imgPath, (unsigned char **)&imgData, &imgWidth, &imgHeight);
|
||||
|
||||
if (!imgData) {
|
||||
printf("Error opening file '%s'\n", imgPath);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
printf("Loaded '%s', %d x %d pixels\n", imgPath, imgWidth, imgHeight);
|
||||
|
||||
checkHost(imgWidth > 1);
|
||||
checkHost(imgHeight > 1);
|
||||
|
||||
Image img;
|
||||
img.size = make_cudaExtent(imgWidth, imgHeight, 0);
|
||||
img.h_data = imgData;
|
||||
images.push_back(img);
|
||||
}
|
||||
|
||||
initAtlasAndImages(&images[0], images.size(), atlasSize);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Program main
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
sdkCreateTimer(&timer);
|
||||
|
||||
pArgc = &argc;
|
||||
pArgv = argv;
|
||||
|
||||
char *ref_file = NULL;
|
||||
|
||||
#if defined(__linux__)
|
||||
setenv("DISPLAY", ":0", 0);
|
||||
#endif
|
||||
|
||||
printf("%s Starting...\n\n", sSDKsample);
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "file")) {
|
||||
fpsLimit = frameCheckNumber;
|
||||
getCmdLineArgumentString(argc, (const char **)argv, "file", &ref_file);
|
||||
}
|
||||
|
||||
srand(15234);
|
||||
|
||||
// use command-line specified CUDA device, otherwise use device with highest
|
||||
// Gflops/s
|
||||
findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
if (!ref_file) {
|
||||
initGL(&argc, argv);
|
||||
|
||||
// OpenGL buffers
|
||||
initGLBuffers();
|
||||
}
|
||||
|
||||
if (!checkCudaCapabilities(3, 0)) {
|
||||
cleanup();
|
||||
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
loadImageData(argv[0]);
|
||||
|
||||
if (ref_file) {
|
||||
runAutoTest(ref_file, argv[0]);
|
||||
}
|
||||
|
||||
printf("Press space to toggle animation\n"
|
||||
"Press '+' and '-' to change lod level\n"
|
||||
"Press 'r' to randomize virtual atlas\n");
|
||||
|
||||
#if defined(__APPLE__) || defined(MACOSX)
|
||||
atexit(cleanup_all);
|
||||
#else
|
||||
glutCloseFunc(cleanup_all);
|
||||
#endif
|
||||
|
||||
glutMainLoop();
|
||||
}
|
||||
66
cpp/3_CUDA_Features/bindlessTexture/bindlessTexture.h
Normal file
66
cpp/3_CUDA_Features/bindlessTexture/bindlessTexture.h
Normal file
@@ -0,0 +1,66 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef _BINDLESSTEXTURE_CU_
|
||||
#define _BINDLESSTEXTURE_CU_
|
||||
|
||||
// includes, cuda
|
||||
#include <cuda_runtime.h>
|
||||
#include <vector_types.h>
|
||||
|
||||
// CUDA utilities and system includes
|
||||
#include <helper_cuda.h>
|
||||
#include <vector_types.h>
|
||||
|
||||
typedef unsigned int uint;
|
||||
typedef unsigned char uchar;
|
||||
|
||||
#pragma pack(push, 4)
|
||||
struct Image
|
||||
{
|
||||
void *h_data;
|
||||
cudaExtent size;
|
||||
cudaResourceType type;
|
||||
cudaArray_t dataArray;
|
||||
cudaMipmappedArray_t mipmapArray;
|
||||
cudaTextureObject_t textureObject;
|
||||
|
||||
Image() { memset(this, 0, sizeof(Image)); }
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
inline void _checkHost(bool test, const char *condition, const char *file, int line, const char *func)
|
||||
{
|
||||
if (!test) {
|
||||
fprintf(stderr, "HOST error at %s:%d (%s) \"%s\" \n", file, line, condition, func);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
#define checkHost(condition) _checkHost(condition, #condition, __FILE__, __LINE__, __FUNCTION__)
|
||||
|
||||
#endif
|
||||
415
cpp/3_CUDA_Features/bindlessTexture/bindlessTexture_kernel.cu
Normal file
415
cpp/3_CUDA_Features/bindlessTexture/bindlessTexture_kernel.cu
Normal file
@@ -0,0 +1,415 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/*
|
||||
This sample has two kernels, one doing the rendering every frame, and
|
||||
another one used to generate the mip map levels at startup.
|
||||
|
||||
For rendering we use a "virtual" texturing approach, where one 2d texture
|
||||
stores pointers to the actual textures used. This can be achieved by the
|
||||
new cudaTextureObject introduced in CUDA 5.0 and requiring sm3+ hardware.
|
||||
|
||||
The mipmap generation kernel uses cudaSurfaceObject and cudaTextureObject
|
||||
passed as kernel arguments to compute the higher mip map level based on
|
||||
the lower.
|
||||
*/
|
||||
|
||||
#ifndef _BINDLESSTEXTURE_KERNEL_CU_
|
||||
#define _BINDLESSTEXTURE_KERNEL_CU_
|
||||
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_math.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <vector>
|
||||
|
||||
#include "bindlessTexture.h"
|
||||
|
||||
// set this to just see the mipmap chain of first image
|
||||
// #define SHOW_MIPMAPS
|
||||
|
||||
// local references to resources
|
||||
|
||||
Image atlasImage;
|
||||
std::vector<Image> contentImages;
|
||||
float highestLod = 1.0f;
|
||||
|
||||
#ifndef MAX
|
||||
#define MAX(a, b) ((a > b) ? a : b)
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
__host__ __device__ __inline__ uint2 encodeTextureObject(cudaTextureObject_t obj)
|
||||
{
|
||||
return make_uint2((uint)(obj & 0xFFFFFFFF), (uint)(obj >> 32));
|
||||
}
|
||||
|
||||
__host__ __device__ __inline__ cudaTextureObject_t decodeTextureObject(uint2 obj)
|
||||
{
|
||||
return (((cudaTextureObject_t)obj.x) | ((cudaTextureObject_t)obj.y) << 32);
|
||||
}
|
||||
|
||||
__device__ __inline__ float4 to_float4(uchar4 vec) { return make_float4(vec.x, vec.y, vec.z, vec.w); }
|
||||
|
||||
__device__ __inline__ uchar4 to_uchar4(float4 vec)
|
||||
{
|
||||
return make_uchar4((uchar)vec.x, (uchar)vec.y, (uchar)vec.z, (uchar)vec.w);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Rendering
|
||||
|
||||
// the atlas texture stores the 64 bit cudaTextureObjects
|
||||
// we use it for "virtual" texturing
|
||||
|
||||
__global__ void d_render(uchar4 *d_output, uint imageW, uint imageH, float lod, cudaTextureObject_t atlasTexture)
|
||||
{
|
||||
uint x = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
uint y = blockIdx.y * blockDim.y + threadIdx.y;
|
||||
|
||||
float u = x / (float)imageW;
|
||||
float v = y / (float)imageH;
|
||||
|
||||
if ((x < imageW) && (y < imageH)) {
|
||||
// read from 2D atlas texture and decode texture object
|
||||
uint2 texCoded = tex2D<uint2>(atlasTexture, u, v);
|
||||
cudaTextureObject_t tex = decodeTextureObject(texCoded);
|
||||
|
||||
// read from cuda texture object, use template to specify what data will be
|
||||
// returned. tex2DLod allows us to pass the lod (mip map level) directly.
|
||||
// There is other functions with CUDA 5, e.g. tex2DGrad, that allow you
|
||||
// to pass derivatives to perform automatic mipmap/anisotropic filtering.
|
||||
float4 color = tex2DLod<float4>(tex, u, 1 - v, lod);
|
||||
// In our sample tex is always valid, but for something like your own
|
||||
// sparse texturing you would need to make sure to handle the zero case.
|
||||
|
||||
// write output color
|
||||
uint i = y * imageW + x;
|
||||
d_output[i] = to_uchar4(color * 255.0);
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" void renderAtlasImage(dim3 gridSize, dim3 blockSize, uchar4 *d_output, uint imageW, uint imageH, float lod)
|
||||
{
|
||||
// psuedo animate lod
|
||||
lod = fmodf(lod, highestLod * 2);
|
||||
lod = highestLod - fabs(lod - highestLod);
|
||||
|
||||
#ifdef SHOW_MIPMAPS
|
||||
lod = 0.0f;
|
||||
#endif
|
||||
|
||||
d_render<<<gridSize, blockSize>>>(d_output, imageW, imageH, lod, atlasImage.textureObject);
|
||||
|
||||
checkCudaErrors(cudaGetLastError());
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// MipMap Generation
|
||||
|
||||
// A key benefit of using the new surface objects is that we don't need any
|
||||
// global binding points anymore. We can directly pass them as function
|
||||
// arguments.
|
||||
|
||||
__global__ void d_mipmap(cudaSurfaceObject_t mipOutput, cudaTextureObject_t mipInput, uint imageW, uint imageH)
|
||||
{
|
||||
uint x = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
uint y = blockIdx.y * blockDim.y + threadIdx.y;
|
||||
|
||||
float px = 1.0 / float(imageW);
|
||||
float py = 1.0 / float(imageH);
|
||||
|
||||
if ((x < imageW) && (y < imageH)) {
|
||||
// take the average of 4 samples
|
||||
|
||||
// we are using the normalized access to make sure non-power-of-two textures
|
||||
// behave well when downsized.
|
||||
float4 color = (tex2D<float4>(mipInput, (x + 0) * px, (y + 0) * py))
|
||||
+ (tex2D<float4>(mipInput, (x + 1) * px, (y + 0) * py))
|
||||
+ (tex2D<float4>(mipInput, (x + 1) * px, (y + 1) * py))
|
||||
+ (tex2D<float4>(mipInput, (x + 0) * px, (y + 1) * py));
|
||||
|
||||
color /= 4.0;
|
||||
color *= 255.0;
|
||||
color = fminf(color, make_float4(255.0));
|
||||
|
||||
surf2Dwrite(to_uchar4(color), mipOutput, x * sizeof(uchar4), y);
|
||||
}
|
||||
}
|
||||
|
||||
void generateMipMaps(cudaMipmappedArray_t mipmapArray, cudaExtent size)
|
||||
{
|
||||
size_t width = size.width;
|
||||
size_t height = size.height;
|
||||
|
||||
#ifdef SHOW_MIPMAPS
|
||||
cudaArray_t levelFirst;
|
||||
checkCudaErrors(cudaGetMipmappedArrayLevel(&levelFirst, mipmapArray, 0));
|
||||
#endif
|
||||
|
||||
uint level = 0;
|
||||
|
||||
while (width != 1 || height != 1) {
|
||||
width /= 2;
|
||||
width = MAX((size_t)1, width);
|
||||
height /= 2;
|
||||
height = MAX((size_t)1, height);
|
||||
|
||||
cudaArray_t levelFrom;
|
||||
checkCudaErrors(cudaGetMipmappedArrayLevel(&levelFrom, mipmapArray, level));
|
||||
cudaArray_t levelTo;
|
||||
checkCudaErrors(cudaGetMipmappedArrayLevel(&levelTo, mipmapArray, level + 1));
|
||||
|
||||
cudaExtent levelToSize;
|
||||
checkCudaErrors(cudaArrayGetInfo(NULL, &levelToSize, NULL, levelTo));
|
||||
checkHost(levelToSize.width == width);
|
||||
checkHost(levelToSize.height == height);
|
||||
checkHost(levelToSize.depth == 0);
|
||||
|
||||
// generate texture object for reading
|
||||
cudaTextureObject_t texInput;
|
||||
cudaResourceDesc texRes;
|
||||
memset(&texRes, 0, sizeof(cudaResourceDesc));
|
||||
|
||||
texRes.resType = cudaResourceTypeArray;
|
||||
texRes.res.array.array = levelFrom;
|
||||
|
||||
cudaTextureDesc texDescr;
|
||||
memset(&texDescr, 0, sizeof(cudaTextureDesc));
|
||||
|
||||
texDescr.normalizedCoords = 1;
|
||||
texDescr.filterMode = cudaFilterModeLinear;
|
||||
|
||||
texDescr.addressMode[0] = cudaAddressModeClamp;
|
||||
texDescr.addressMode[1] = cudaAddressModeClamp;
|
||||
texDescr.addressMode[2] = cudaAddressModeClamp;
|
||||
|
||||
texDescr.readMode = cudaReadModeNormalizedFloat;
|
||||
|
||||
checkCudaErrors(cudaCreateTextureObject(&texInput, &texRes, &texDescr, NULL));
|
||||
|
||||
// generate surface object for writing
|
||||
|
||||
cudaSurfaceObject_t surfOutput;
|
||||
cudaResourceDesc surfRes;
|
||||
memset(&surfRes, 0, sizeof(cudaResourceDesc));
|
||||
surfRes.resType = cudaResourceTypeArray;
|
||||
surfRes.res.array.array = levelTo;
|
||||
|
||||
checkCudaErrors(cudaCreateSurfaceObject(&surfOutput, &surfRes));
|
||||
|
||||
// run mipmap kernel
|
||||
dim3 blockSize(16, 16, 1);
|
||||
dim3 gridSize(((uint)width + blockSize.x - 1) / blockSize.x, ((uint)height + blockSize.y - 1) / blockSize.y, 1);
|
||||
|
||||
d_mipmap<<<gridSize, blockSize>>>(surfOutput, texInput, (uint)width, (uint)height);
|
||||
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
checkCudaErrors(cudaGetLastError());
|
||||
|
||||
checkCudaErrors(cudaDestroySurfaceObject(surfOutput));
|
||||
|
||||
checkCudaErrors(cudaDestroyTextureObject(texInput));
|
||||
|
||||
#ifdef SHOW_MIPMAPS
|
||||
// we blit the current mipmap back into first level
|
||||
cudaMemcpy3DParms copyParams = {0};
|
||||
copyParams.dstArray = levelFirst;
|
||||
copyParams.srcArray = levelTo;
|
||||
copyParams.extent = make_cudaExtent(width, height, 1);
|
||||
copyParams.kind = cudaMemcpyDeviceToDevice;
|
||||
checkCudaErrors(cudaMemcpy3D(©Params));
|
||||
#endif
|
||||
|
||||
level++;
|
||||
}
|
||||
}
|
||||
|
||||
uint getMipMapLevels(cudaExtent size)
|
||||
{
|
||||
size_t sz = MAX(MAX(size.width, size.height), size.depth);
|
||||
|
||||
uint levels = 0;
|
||||
|
||||
while (sz) {
|
||||
sz /= 2;
|
||||
levels++;
|
||||
}
|
||||
|
||||
return levels;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Initalization
|
||||
|
||||
extern "C" void randomizeAtlas()
|
||||
{
|
||||
uint2 *h_data = (uint2 *)atlasImage.h_data;
|
||||
|
||||
// assign random texture object handles to our atlas image tiles
|
||||
for (size_t i = 0; i < atlasImage.size.width * atlasImage.size.height; i++) {
|
||||
#ifdef SHOW_MIPMAPS
|
||||
h_data[i] = encodeTextureObject(contentImages[0].textureObject);
|
||||
#else
|
||||
h_data[i] = encodeTextureObject(contentImages[rand() % contentImages.size()].textureObject);
|
||||
#endif
|
||||
}
|
||||
|
||||
// copy data to atlas array
|
||||
cudaMemcpy3DParms copyParams = {0};
|
||||
copyParams.srcPtr = make_cudaPitchedPtr(
|
||||
atlasImage.h_data, atlasImage.size.width * sizeof(uint2), atlasImage.size.width, atlasImage.size.height);
|
||||
copyParams.dstArray = atlasImage.dataArray;
|
||||
copyParams.extent = atlasImage.size;
|
||||
copyParams.extent.depth = 1;
|
||||
copyParams.kind = cudaMemcpyHostToDevice;
|
||||
checkCudaErrors(cudaMemcpy3D(©Params));
|
||||
};
|
||||
|
||||
extern "C" void deinitAtlasAndImages()
|
||||
{
|
||||
for (size_t i = 0; i < contentImages.size(); i++) {
|
||||
Image &image = contentImages[i];
|
||||
|
||||
if (image.h_data) {
|
||||
free(image.h_data);
|
||||
}
|
||||
|
||||
if (image.textureObject) {
|
||||
checkCudaErrors(cudaDestroyTextureObject(image.textureObject));
|
||||
}
|
||||
|
||||
if (image.mipmapArray) {
|
||||
checkCudaErrors(cudaFreeMipmappedArray(image.mipmapArray));
|
||||
}
|
||||
}
|
||||
|
||||
if (atlasImage.h_data) {
|
||||
free(atlasImage.h_data);
|
||||
}
|
||||
|
||||
if (atlasImage.textureObject) {
|
||||
checkCudaErrors(cudaDestroyTextureObject(atlasImage.textureObject));
|
||||
}
|
||||
|
||||
if (atlasImage.dataArray) {
|
||||
checkCudaErrors(cudaFreeArray(atlasImage.dataArray));
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" void initAtlasAndImages(const Image *images, size_t numImages, cudaExtent atlasSize)
|
||||
{
|
||||
// create individual textures
|
||||
contentImages.resize(numImages);
|
||||
|
||||
for (size_t i = 0; i < numImages; i++) {
|
||||
Image &image = contentImages[i];
|
||||
image.size = images[i].size;
|
||||
image.size.depth = 0;
|
||||
image.type = cudaResourceTypeMipmappedArray;
|
||||
|
||||
// how many mipmaps we need
|
||||
uint levels = getMipMapLevels(image.size);
|
||||
highestLod = MAX(highestLod, (float)levels - 1);
|
||||
|
||||
cudaChannelFormatDesc desc = cudaCreateChannelDesc<uchar4>();
|
||||
checkCudaErrors(cudaMallocMipmappedArray(&image.mipmapArray, &desc, image.size, levels));
|
||||
|
||||
// upload level 0
|
||||
cudaArray_t level0;
|
||||
checkCudaErrors(cudaGetMipmappedArrayLevel(&level0, image.mipmapArray, 0));
|
||||
|
||||
cudaMemcpy3DParms copyParams = {0};
|
||||
copyParams.srcPtr = make_cudaPitchedPtr(
|
||||
images[i].h_data, image.size.width * sizeof(uchar4), image.size.width, image.size.height);
|
||||
copyParams.dstArray = level0;
|
||||
copyParams.extent = image.size;
|
||||
copyParams.extent.depth = 1;
|
||||
copyParams.kind = cudaMemcpyHostToDevice;
|
||||
checkCudaErrors(cudaMemcpy3D(©Params));
|
||||
|
||||
// compute rest of mipmaps based on level 0
|
||||
generateMipMaps(image.mipmapArray, image.size);
|
||||
|
||||
// generate bindless texture object
|
||||
|
||||
cudaResourceDesc resDescr;
|
||||
memset(&resDescr, 0, sizeof(cudaResourceDesc));
|
||||
|
||||
resDescr.resType = cudaResourceTypeMipmappedArray;
|
||||
resDescr.res.mipmap.mipmap = image.mipmapArray;
|
||||
|
||||
cudaTextureDesc texDescr;
|
||||
memset(&texDescr, 0, sizeof(cudaTextureDesc));
|
||||
|
||||
texDescr.normalizedCoords = 1;
|
||||
texDescr.filterMode = cudaFilterModeLinear;
|
||||
texDescr.mipmapFilterMode = cudaFilterModeLinear;
|
||||
|
||||
texDescr.addressMode[0] = cudaAddressModeClamp;
|
||||
texDescr.addressMode[1] = cudaAddressModeClamp;
|
||||
texDescr.addressMode[2] = cudaAddressModeClamp;
|
||||
|
||||
texDescr.maxMipmapLevelClamp = float(levels - 1);
|
||||
|
||||
texDescr.readMode = cudaReadModeNormalizedFloat;
|
||||
|
||||
checkCudaErrors(cudaCreateTextureObject(&image.textureObject, &resDescr, &texDescr, NULL));
|
||||
}
|
||||
|
||||
// create atlas array
|
||||
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<uint2>();
|
||||
checkCudaErrors(cudaMallocArray(&atlasImage.dataArray, &channelDesc, atlasSize.width, atlasSize.height));
|
||||
atlasImage.h_data = malloc(atlasSize.width * atlasSize.height * sizeof(uint2));
|
||||
atlasImage.type = cudaResourceTypeArray;
|
||||
atlasImage.size = atlasSize;
|
||||
|
||||
cudaResourceDesc texRes;
|
||||
memset(&texRes, 0, sizeof(cudaResourceDesc));
|
||||
|
||||
texRes.resType = cudaResourceTypeArray;
|
||||
texRes.res.array.array = atlasImage.dataArray;
|
||||
|
||||
cudaTextureDesc texDescr;
|
||||
memset(&texDescr, 0, sizeof(cudaTextureDesc));
|
||||
|
||||
texDescr.normalizedCoords = true;
|
||||
texDescr.filterMode = cudaFilterModePoint;
|
||||
texDescr.addressMode[0] = cudaAddressModeClamp;
|
||||
texDescr.addressMode[1] = cudaAddressModeClamp;
|
||||
texDescr.addressMode[1] = cudaAddressModeClamp;
|
||||
texDescr.readMode = cudaReadModeElementType;
|
||||
|
||||
checkCudaErrors(cudaCreateTextureObject(&atlasImage.textureObject, &texRes, &texDescr, NULL));
|
||||
|
||||
randomizeAtlas();
|
||||
}
|
||||
|
||||
#endif // #ifndef _SIMPLETEXTURE3D_KERNEL_CU_
|
||||
3530
cpp/3_CUDA_Features/bindlessTexture/data/flower.ppm
Normal file
3530
cpp/3_CUDA_Features/bindlessTexture/data/flower.ppm
Normal file
File diff suppressed because one or more lines are too long
BIN
cpp/3_CUDA_Features/bindlessTexture/data/person.ppm
Normal file
BIN
cpp/3_CUDA_Features/bindlessTexture/data/person.ppm
Normal file
Binary file not shown.
BIN
cpp/3_CUDA_Features/bindlessTexture/data/ref_bindlessTexture.bin
Normal file
BIN
cpp/3_CUDA_Features/bindlessTexture/data/ref_bindlessTexture.bin
Normal file
Binary file not shown.
BIN
cpp/3_CUDA_Features/bindlessTexture/data/sponge.ppm
Normal file
BIN
cpp/3_CUDA_Features/bindlessTexture/data/sponge.ppm
Normal file
Binary file not shown.
BIN
cpp/3_CUDA_Features/bindlessTexture/doc/sshot_lg.JPG
Normal file
BIN
cpp/3_CUDA_Features/bindlessTexture/doc/sshot_lg.JPG
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
BIN
cpp/3_CUDA_Features/bindlessTexture/doc/sshot_md.JPG
Normal file
BIN
cpp/3_CUDA_Features/bindlessTexture/doc/sshot_md.JPG
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
BIN
cpp/3_CUDA_Features/bindlessTexture/doc/sshot_sm.JPG
Normal file
BIN
cpp/3_CUDA_Features/bindlessTexture/doc/sshot_sm.JPG
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.0 KiB |
18
cpp/3_CUDA_Features/cdpAdvancedQuicksort/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/cdpAdvancedQuicksort/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/cdpAdvancedQuicksort/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/cdpAdvancedQuicksort/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
44
cpp/3_CUDA_Features/cdpAdvancedQuicksort/CMakeLists.txt
Normal file
44
cpp/3_CUDA_Features/cdpAdvancedQuicksort/CMakeLists.txt
Normal file
@@ -0,0 +1,44 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(cdpAdvancedQuicksort LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# The aarch64/sbsa_aarch64 CUDA toolkit are support on Tegra since 13.0, so need to check which version of the toolkit is installed
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-linux" _aarch64_linux_ctk)
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-qnx" _aarch64_qnx_ctk)
|
||||
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" AND (NOT _aarch64_linux_ctk EQUAL -1 OR NOT _aarch64_qnx_ctk EQUAL -1))
|
||||
set(CMAKE_CUDA_ARCHITECTURES 87 110)
|
||||
else()
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 89 90 100 110 120)
|
||||
endif()
|
||||
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -maxrregcount=64") # Limit register usage to 64 for the 'big_bitonicsort kernel
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for cdpAdvancedQuicksort
|
||||
add_executable(cdpAdvancedQuicksort cdpAdvancedQuicksort.cu cdpBitonicSort.cu)
|
||||
|
||||
target_compile_options(cdpAdvancedQuicksort PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(cdpAdvancedQuicksort PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(cdpAdvancedQuicksort PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
34
cpp/3_CUDA_Features/cdpAdvancedQuicksort/README.md
Normal file
34
cpp/3_CUDA_Features/cdpAdvancedQuicksort/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# cdpAdvancedQuicksort - Advanced Quicksort (CUDA Dynamic Parallelism)
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates an advanced quicksort implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Cooperative Groups, CUDA Dynamic Parallelism
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaStreamCreateWithFlags, cudaMemcpy, cudaMemcpyAsync, cudaFree, cudaGetErrorString, cudaGetLastError, cudaPeekAtLastError, cudaDeviceSynchronize, cudaEventRecord, cudaMemset, cudaMalloc, cudaEventElapsedTime, cudaGetDeviceProperties, cudaEventCreate
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[CDP](../../../README.md#cuda-dynamic-parallellism)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
584
cpp/3_CUDA_Features/cdpAdvancedQuicksort/cdpAdvancedQuicksort.cu
Normal file
584
cpp/3_CUDA_Features/cdpAdvancedQuicksort/cdpAdvancedQuicksort.cu
Normal file
@@ -0,0 +1,584 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// cdpAdvancedQuicksort.cu
|
||||
//
|
||||
// Implementation of a parallel quicksort in CUDA. It comes in
|
||||
// several parts:
|
||||
//
|
||||
// 1. A small-set insertion sort. We do this on any set with <=32 elements
|
||||
// 2. A partitioning kernel, which - given a pivot - separates an input
|
||||
// array into elements <=pivot, and >pivot. Two quicksorts will then
|
||||
// be launched to resolve each of these.
|
||||
// 3. A quicksort co-ordinator, which figures out what kernels to launch
|
||||
// and when.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
#include <cooperative_groups.h>
|
||||
#include <thrust/device_vector.h>
|
||||
#include <thrust/random.h>
|
||||
|
||||
namespace cg = cooperative_groups;
|
||||
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_string.h>
|
||||
|
||||
#include "cdpQuicksort.h"
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Inline PTX call to return index of highest non-zero bit in a word
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
static __device__ __forceinline__ unsigned int __qsflo(unsigned int word)
|
||||
{
|
||||
unsigned int ret;
|
||||
asm volatile("bfind.u32 %0, %1;" : "=r"(ret) : "r"(word));
|
||||
return ret;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// ringbufAlloc
|
||||
//
|
||||
// Allocates from a ringbuffer. Allows for not failing when we run out
|
||||
// of stack for tracking the offset counts for each sort subsection.
|
||||
//
|
||||
// We use the atomicMax trick to allow out-of-order retirement. If we
|
||||
// hit the size limit on the ringbuffer, then we spin-wait for people
|
||||
// to complete.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
template <typename T> static __device__ T *ringbufAlloc(qsortRingbuf *ringbuf)
|
||||
{
|
||||
// Wait for there to be space in the ring buffer. We'll retry only a fixed
|
||||
// number of times and then fail, to avoid an out-of-memory deadlock.
|
||||
unsigned int loop = 10000;
|
||||
|
||||
while (((ringbuf->head - ringbuf->tail) >= ringbuf->stacksize) && (loop-- > 0))
|
||||
;
|
||||
|
||||
if (loop == 0)
|
||||
return NULL;
|
||||
|
||||
// Note that the element includes a little index book-keeping, for freeing
|
||||
// later.
|
||||
unsigned int index = atomicAdd((unsigned int *)&ringbuf->head, 1);
|
||||
T *ret = (T *)(ringbuf->stackbase) + (index & (ringbuf->stacksize - 1));
|
||||
ret->index = index;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// ringBufFree
|
||||
//
|
||||
// Releases an element from the ring buffer. If every element is released
|
||||
// up to and including this one, we can advance the tail to indicate that
|
||||
// space is now available.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
template <typename T> static __device__ void ringbufFree(qsortRingbuf *ringbuf, T *data)
|
||||
{
|
||||
unsigned int index = data->index; // Non-wrapped index to free
|
||||
unsigned int count = atomicAdd((unsigned int *)&(ringbuf->count), 1) + 1;
|
||||
unsigned int max = atomicMax((unsigned int *)&(ringbuf->max), index + 1);
|
||||
|
||||
// Update the tail if need be. Note we update "max" to be the new value in
|
||||
// ringbuf->max
|
||||
if (max < (index + 1))
|
||||
max = index + 1;
|
||||
|
||||
if (max == count)
|
||||
atomicMax((unsigned int *)&(ringbuf->tail), count);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// qsort_warp
|
||||
//
|
||||
// Simplest possible implementation, does a per-warp quicksort with no
|
||||
// inter-warp
|
||||
// communication. This has a high atomic issue rate, but the rest should
|
||||
// actually
|
||||
// be fairly quick because of low work per thread.
|
||||
//
|
||||
// A warp finds its section of the data, then writes all data <pivot to one
|
||||
// buffer and all data >pivot to the other. Atomics are used to get a unique
|
||||
// section of the buffer.
|
||||
//
|
||||
// Obvious optimisation: do multiple chunks per warp, to increase in-flight
|
||||
// loads
|
||||
// and cover the instruction overhead.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
__global__ void qsort_warp(unsigned *indata,
|
||||
unsigned *outdata,
|
||||
unsigned int offset,
|
||||
unsigned int len,
|
||||
qsortAtomicData *atomicData,
|
||||
qsortRingbuf *atomicDataStack,
|
||||
unsigned int source_is_indata,
|
||||
unsigned int depth)
|
||||
{
|
||||
// Handle to thread block group
|
||||
cg::thread_block cta = cg::this_thread_block();
|
||||
// Find my data offset, based on warp ID
|
||||
unsigned int thread_id = threadIdx.x + (blockIdx.x << QSORT_BLOCKSIZE_SHIFT);
|
||||
// unsigned int warp_id = threadIdx.x >> 5; // Used for debug only
|
||||
unsigned int lane_id = threadIdx.x & (warpSize - 1);
|
||||
|
||||
// Exit if I'm outside the range of sort to be done
|
||||
if (thread_id >= len)
|
||||
return;
|
||||
|
||||
//
|
||||
// First part of the algorithm. Each warp counts the number of elements that
|
||||
// are
|
||||
// greater/less than the pivot.
|
||||
//
|
||||
// When a warp knows its count, it updates an atomic counter.
|
||||
//
|
||||
|
||||
// Read in the data and the pivot. Arbitrary pivot selection for now.
|
||||
unsigned pivot = indata[offset + len / 2];
|
||||
unsigned data = indata[offset + thread_id];
|
||||
|
||||
// Count how many are <= and how many are > pivot.
|
||||
// If all are <= pivot then we adjust the comparison
|
||||
// because otherwise the sort will move nothing and
|
||||
// we'll iterate forever.
|
||||
cg::coalesced_group active = cg::coalesced_threads();
|
||||
unsigned int greater = (data > pivot);
|
||||
unsigned int gt_mask = active.ballot(greater);
|
||||
|
||||
if (gt_mask == 0) {
|
||||
greater = (data >= pivot);
|
||||
gt_mask = active.ballot(greater); // Must re-ballot for adjusted comparator
|
||||
}
|
||||
|
||||
unsigned int lt_mask = active.ballot(!greater);
|
||||
unsigned int gt_count = __popc(gt_mask);
|
||||
unsigned int lt_count = __popc(lt_mask);
|
||||
|
||||
// Atomically adjust the lt_ and gt_offsets by this amount. Only one thread
|
||||
// need do this. Share the result using shfl
|
||||
unsigned int lt_offset, gt_offset;
|
||||
|
||||
if (lane_id == 0) {
|
||||
if (lt_count > 0)
|
||||
lt_offset = atomicAdd((unsigned int *)&atomicData->lt_offset, lt_count);
|
||||
|
||||
if (gt_count > 0)
|
||||
gt_offset = len - (atomicAdd((unsigned int *)&atomicData->gt_offset, gt_count) + gt_count);
|
||||
}
|
||||
|
||||
lt_offset = active.shfl((int)lt_offset, 0); // Everyone pulls the offsets from lane 0
|
||||
gt_offset = active.shfl((int)gt_offset, 0);
|
||||
|
||||
// Now compute my own personal offset within this. I need to know how many
|
||||
// threads with a lane ID less than mine are going to write to the same buffer
|
||||
// as me. We can use popc to implement a single-operation warp scan in this
|
||||
// case.
|
||||
unsigned lane_mask_lt;
|
||||
asm("mov.u32 %0, %%lanemask_lt;" : "=r"(lane_mask_lt));
|
||||
unsigned int my_mask = greater ? gt_mask : lt_mask;
|
||||
unsigned int my_offset = __popc(my_mask & lane_mask_lt);
|
||||
|
||||
// Move data.
|
||||
my_offset += greater ? gt_offset : lt_offset;
|
||||
outdata[offset + my_offset] = data;
|
||||
|
||||
// Count up if we're the last warp in. If so, then Kepler will launch the next
|
||||
// set of sorts directly from here.
|
||||
if (lane_id == 0) {
|
||||
// Count "elements written". If I wrote the last one, then trigger the next
|
||||
// qsorts
|
||||
unsigned int mycount = lt_count + gt_count;
|
||||
|
||||
if (atomicAdd((unsigned int *)&atomicData->sorted_count, mycount) + mycount == len) {
|
||||
// We're the last warp to do any sorting. Therefore it's up to us to
|
||||
// launch the next stage.
|
||||
unsigned int lt_len = atomicData->lt_offset;
|
||||
unsigned int gt_len = atomicData->gt_offset;
|
||||
|
||||
cudaStream_t lstream, rstream;
|
||||
cudaStreamCreateWithFlags(&lstream, cudaStreamNonBlocking);
|
||||
cudaStreamCreateWithFlags(&rstream, cudaStreamNonBlocking);
|
||||
|
||||
// Begin by freeing our atomicData storage. It's better for the ringbuffer
|
||||
// algorithm
|
||||
// if we free when we're done, rather than re-using (makes for less
|
||||
// fragmentation).
|
||||
ringbufFree<qsortAtomicData>(atomicDataStack, atomicData);
|
||||
|
||||
// Exceptional case: if "lt_len" is zero, then all values in the batch
|
||||
// are equal. We are then done (may need to copy into correct buffer,
|
||||
// though)
|
||||
if (lt_len == 0) {
|
||||
if (source_is_indata)
|
||||
cudaMemcpyAsync(indata + offset,
|
||||
outdata + offset,
|
||||
gt_len * sizeof(unsigned),
|
||||
cudaMemcpyDeviceToDevice,
|
||||
lstream);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Start with lower half first
|
||||
if (lt_len > BITONICSORT_LEN) {
|
||||
// If we've exceeded maximum depth, fall through to backup
|
||||
// big_bitonicsort
|
||||
if (depth >= QSORT_MAXDEPTH) {
|
||||
// The final bitonic stage sorts in-place in "outdata". We therefore
|
||||
// re-use "indata" as the out-of-range tracking buffer. For (2^n)+1
|
||||
// elements we need (2^(n+1)) bytes of oor buffer. The backup qsort
|
||||
// buffer is at least this large when sizeof(QTYPE) >= 2.
|
||||
big_bitonicsort<<<1, BITONICSORT_LEN, 0, lstream>>>(
|
||||
outdata, source_is_indata ? indata : outdata, indata, offset, lt_len);
|
||||
}
|
||||
else {
|
||||
// Launch another quicksort. We need to allocate more storage for the
|
||||
// atomic data.
|
||||
if ((atomicData = ringbufAlloc<qsortAtomicData>(atomicDataStack)) == NULL)
|
||||
printf("Stack-allocation error. Failing left child launch.\n");
|
||||
else {
|
||||
atomicData->lt_offset = atomicData->gt_offset = atomicData->sorted_count = 0;
|
||||
unsigned int numblocks =
|
||||
(unsigned int)(lt_len + (QSORT_BLOCKSIZE - 1)) >> QSORT_BLOCKSIZE_SHIFT;
|
||||
qsort_warp<<<numblocks, QSORT_BLOCKSIZE, 0, lstream>>>(
|
||||
outdata, indata, offset, lt_len, atomicData, atomicDataStack, !source_is_indata, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (lt_len > 1) {
|
||||
// Final stage uses a bitonic sort instead. It's important to
|
||||
// make sure the final stage ends up in the correct (original) buffer.
|
||||
// We launch the smallest power-of-2 number of threads that we can.
|
||||
unsigned int bitonic_len = 1 << (__qsflo(lt_len - 1U) + 1);
|
||||
bitonicsort<<<1, bitonic_len, 0, lstream>>>(
|
||||
outdata, source_is_indata ? indata : outdata, offset, lt_len);
|
||||
}
|
||||
// Finally, if we sorted just one single element, we must still make
|
||||
// sure that it winds up in the correct place.
|
||||
else if (source_is_indata && (lt_len == 1))
|
||||
indata[offset] = outdata[offset];
|
||||
|
||||
if (cudaPeekAtLastError() != cudaSuccess)
|
||||
printf("Left-side launch fail: %s\n", cudaGetErrorString(cudaGetLastError()));
|
||||
|
||||
// Now the upper half.
|
||||
if (gt_len > BITONICSORT_LEN) {
|
||||
// If we've exceeded maximum depth, fall through to backup
|
||||
// big_bitonicsort
|
||||
if (depth >= QSORT_MAXDEPTH)
|
||||
big_bitonicsort<<<1, BITONICSORT_LEN, 0, rstream>>>(
|
||||
outdata, source_is_indata ? indata : outdata, indata, offset + lt_len, gt_len);
|
||||
else {
|
||||
// Allocate new atomic storage for this launch
|
||||
if ((atomicData = ringbufAlloc<qsortAtomicData>(atomicDataStack)) == NULL)
|
||||
printf("Stack allocation error! Failing right-side launch.\n");
|
||||
else {
|
||||
atomicData->lt_offset = atomicData->gt_offset = atomicData->sorted_count = 0;
|
||||
unsigned int numblocks =
|
||||
(unsigned int)(gt_len + (QSORT_BLOCKSIZE - 1)) >> QSORT_BLOCKSIZE_SHIFT;
|
||||
qsort_warp<<<numblocks, QSORT_BLOCKSIZE, 0, rstream>>>(outdata,
|
||||
indata,
|
||||
offset + lt_len,
|
||||
gt_len,
|
||||
atomicData,
|
||||
atomicDataStack,
|
||||
!source_is_indata,
|
||||
depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (gt_len > 1) {
|
||||
unsigned int bitonic_len = 1 << (__qsflo(gt_len - 1U) + 1);
|
||||
bitonicsort<<<1, bitonic_len, 0, rstream>>>(
|
||||
outdata, source_is_indata ? indata : outdata, offset + lt_len, gt_len);
|
||||
}
|
||||
else if (source_is_indata && (gt_len == 1))
|
||||
indata[offset + lt_len] = outdata[offset + lt_len];
|
||||
|
||||
if (cudaPeekAtLastError() != cudaSuccess)
|
||||
printf("Right-side launch fail: %s\n", cudaGetErrorString(cudaGetLastError()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// run_quicksort
|
||||
//
|
||||
// Host-side code to run the Kepler version of quicksort. It's pretty
|
||||
// simple, because all launch control is handled on the device via CDP.
|
||||
//
|
||||
// All parallel quicksorts require an equal-sized scratch buffer. This
|
||||
// must be passed in ahead of time.
|
||||
//
|
||||
// Returns the time elapsed for the sort.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
float run_quicksort_cdp(unsigned *gpudata, unsigned *scratchdata, unsigned int count, cudaStream_t stream)
|
||||
{
|
||||
unsigned int stacksize = QSORT_STACK_ELEMS;
|
||||
|
||||
// This is the stack, for atomic tracking of each sort's status
|
||||
qsortAtomicData *gpustack;
|
||||
checkCudaErrors(cudaMalloc((void **)&gpustack, stacksize * sizeof(qsortAtomicData)));
|
||||
checkCudaErrors(cudaMemset(gpustack, 0, sizeof(qsortAtomicData))); // Only need set first entry to 0
|
||||
|
||||
// Create the memory ringbuffer used for handling the stack.
|
||||
// Initialise everything to where it needs to be.
|
||||
qsortRingbuf buf;
|
||||
qsortRingbuf *ringbuf;
|
||||
checkCudaErrors(cudaMalloc((void **)&ringbuf, sizeof(qsortRingbuf)));
|
||||
buf.head = 1; // We start with one allocation
|
||||
buf.tail = 0;
|
||||
buf.count = 0;
|
||||
buf.max = 0;
|
||||
buf.stacksize = stacksize;
|
||||
buf.stackbase = gpustack;
|
||||
checkCudaErrors(cudaMemcpy(ringbuf, &buf, sizeof(buf), cudaMemcpyHostToDevice));
|
||||
|
||||
// Timing events...
|
||||
cudaEvent_t ev1, ev2;
|
||||
checkCudaErrors(cudaEventCreate(&ev1));
|
||||
checkCudaErrors(cudaEventCreate(&ev2));
|
||||
checkCudaErrors(cudaEventRecord(ev1));
|
||||
|
||||
// Now we trivially launch the qsort kernel
|
||||
if (count > BITONICSORT_LEN) {
|
||||
unsigned int numblocks = (unsigned int)(count + (QSORT_BLOCKSIZE - 1)) >> QSORT_BLOCKSIZE_SHIFT;
|
||||
qsort_warp<<<numblocks, QSORT_BLOCKSIZE, 0, stream>>>(
|
||||
gpudata, scratchdata, 0U, count, gpustack, ringbuf, true, 0);
|
||||
}
|
||||
else {
|
||||
bitonicsort<<<1, BITONICSORT_LEN>>>(gpudata, gpudata, 0, count);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaGetLastError());
|
||||
checkCudaErrors(cudaEventRecord(ev2));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
float elapse = 0.0f;
|
||||
|
||||
if (cudaPeekAtLastError() != cudaSuccess)
|
||||
printf("Launch failure: %s\n", cudaGetErrorString(cudaGetLastError()));
|
||||
else
|
||||
checkCudaErrors(cudaEventElapsedTime(&elapse, ev1, ev2));
|
||||
|
||||
// Sanity check that the stack allocator is doing the right thing
|
||||
checkCudaErrors(cudaMemcpy(&buf, ringbuf, sizeof(*ringbuf), cudaMemcpyDeviceToHost));
|
||||
|
||||
if (count > BITONICSORT_LEN && buf.head != buf.tail) {
|
||||
printf("Stack allocation error!\nRingbuf:\n");
|
||||
printf("\t head = %u\n", buf.head);
|
||||
printf("\t tail = %u\n", buf.tail);
|
||||
printf("\tcount = %u\n", buf.count);
|
||||
printf("\t max = %u\n", buf.max);
|
||||
}
|
||||
|
||||
// Release our stack data once we're done
|
||||
checkCudaErrors(cudaFree(ringbuf));
|
||||
checkCudaErrors(cudaFree(gpustack));
|
||||
|
||||
return elapse;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
int run_qsort(unsigned int size, int seed, int debug, int loop, int verbose)
|
||||
{
|
||||
if (seed > 0)
|
||||
srand(seed);
|
||||
|
||||
// Create and set up our test
|
||||
unsigned *gpudata, *scratchdata;
|
||||
checkCudaErrors(cudaMalloc((void **)&gpudata, size * sizeof(unsigned)));
|
||||
checkCudaErrors(cudaMalloc((void **)&scratchdata, size * sizeof(unsigned)));
|
||||
|
||||
// Create CPU data.
|
||||
unsigned *data = new unsigned[size];
|
||||
unsigned int min = loop ? loop : size;
|
||||
unsigned int max = size;
|
||||
loop = (loop == 0) ? 1 : loop;
|
||||
|
||||
for (size = min; size <= max; size += loop) {
|
||||
if (verbose)
|
||||
printf(" Input: ");
|
||||
|
||||
for (unsigned int i = 0; i < size; i++) {
|
||||
// Build data 8 bits at a time
|
||||
data[i] = 0;
|
||||
char *ptr = (char *)&(data[i]);
|
||||
|
||||
for (unsigned j = 0; j < sizeof(unsigned); j++) {
|
||||
// Easy-to-read data in debug mode
|
||||
if (debug) {
|
||||
*ptr++ = (char)(rand() % 10);
|
||||
break;
|
||||
}
|
||||
|
||||
*ptr++ = (char)(rand() & 255);
|
||||
}
|
||||
|
||||
if (verbose) {
|
||||
if (i && !(i % 32))
|
||||
printf("\n ");
|
||||
|
||||
printf("%u ", data[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (verbose)
|
||||
printf("\n");
|
||||
|
||||
checkCudaErrors(cudaMemcpy(gpudata, data, size * sizeof(unsigned), cudaMemcpyHostToDevice));
|
||||
|
||||
// So we're now populated and ready to go! We size our launch as
|
||||
// blocks of up to BLOCKSIZE threads, and appropriate grid size.
|
||||
// One thread is launched per element.
|
||||
float elapse;
|
||||
elapse = run_quicksort_cdp(gpudata, scratchdata, size, NULL);
|
||||
|
||||
// run_bitonicsort<SORTTYPE>(gpudata, scratchdata, size, verbose);
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Copy back the data and verify correct sort
|
||||
checkCudaErrors(cudaMemcpy(data, gpudata, size * sizeof(unsigned), cudaMemcpyDeviceToHost));
|
||||
|
||||
if (verbose) {
|
||||
printf("Output: ");
|
||||
|
||||
for (unsigned int i = 0; i < size; i++) {
|
||||
if (i && !(i % 32))
|
||||
printf("\n ");
|
||||
|
||||
printf("%u ", data[i]);
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
unsigned int check;
|
||||
|
||||
for (check = 1; check < size; check++) {
|
||||
if (data[check] < data[check - 1]) {
|
||||
printf("FAILED at element: %d\n", check);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (check != size) {
|
||||
printf(" cdpAdvancedQuicksort FAILED\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
else
|
||||
printf(" cdpAdvancedQuicksort PASSED\n");
|
||||
|
||||
// Display the time between event recordings
|
||||
printf("Sorted %u elems in %.3f ms (%.3f Melems/sec)\n", size, elapse, (float)size / (elapse * 1000.0f));
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// Release everything and we're done
|
||||
checkCudaErrors(cudaFree(scratchdata));
|
||||
checkCudaErrors(cudaFree(gpudata));
|
||||
delete (data);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void usage()
|
||||
{
|
||||
printf("Syntax: cdpAdvancedQuicksort [-size=<num>] [-seed=<num>] [-debug] "
|
||||
"[-loop-step=<num>] [-verbose]\n");
|
||||
printf("If loop_step is non-zero, will run from 1->array_len in steps of "
|
||||
"loop_step\n");
|
||||
}
|
||||
|
||||
// Host side entry
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
int size = 1000000;
|
||||
unsigned int seed = 0;
|
||||
int debug = 0;
|
||||
int loop = 0;
|
||||
int verbose = 0;
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "help") || checkCmdLineFlag(argc, (const char **)argv, "h")) {
|
||||
usage();
|
||||
printf("&&&& cdpAdvancedQuicksort WAIVED\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "size")) {
|
||||
size = getCmdLineArgumentInt(argc, (const char **)argv, "size");
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "seed")) {
|
||||
seed = getCmdLineArgumentInt(argc, (const char **)argv, "seed");
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "loop-step")) {
|
||||
loop = getCmdLineArgumentInt(argc, (const char **)argv, "loop-step");
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "debug")) {
|
||||
debug = 1;
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "verbose")) {
|
||||
verbose = 1;
|
||||
}
|
||||
|
||||
// Get device properties
|
||||
int cuda_device = findCudaDevice(argc, (const char **)argv);
|
||||
cudaDeviceProp properties;
|
||||
checkCudaErrors(cudaGetDeviceProperties(&properties, cuda_device));
|
||||
int cdpCapable = (properties.major == 3 && properties.minor >= 5) || properties.major >= 4;
|
||||
|
||||
printf("GPU device %s has compute capabilities (SM %d.%d)\n", properties.name, properties.major, properties.minor);
|
||||
|
||||
if (!cdpCapable) {
|
||||
printf("cdpAdvancedQuicksort requires SM 3.5 or higher to use CUDA Dynamic "
|
||||
"Parallelism. Exiting...\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
printf("Running qsort on %d elements with seed %d, on %s\n", size, seed, properties.name);
|
||||
|
||||
// Increase the pending kernel launch limit
|
||||
cudaDeviceSetLimit(cudaLimitDevRuntimePendingLaunchCount, 4096);
|
||||
|
||||
run_qsort(size, seed, debug, loop, verbose);
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
290
cpp/3_CUDA_Features/cdpAdvancedQuicksort/cdpBitonicSort.cu
Normal file
290
cpp/3_CUDA_Features/cdpAdvancedQuicksort/cdpBitonicSort.cu
Normal file
@@ -0,0 +1,290 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// This is a basic, recursive bitonic sort taken from
|
||||
// http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/oddn.htm
|
||||
//
|
||||
// The parallel code is based on:
|
||||
// http://www.tools-of-computing.com/tc/CS/Sorts/bitonic_sort.htm
|
||||
//
|
||||
// The multithread code is from me.
|
||||
|
||||
#include <cooperative_groups.h>
|
||||
#include <stdio.h>
|
||||
|
||||
namespace cg = cooperative_groups;
|
||||
|
||||
#include "cdpQuicksort.h"
|
||||
|
||||
// Inline PTX call to return index of highest non-zero bit in a word
|
||||
static __device__ __forceinline__ unsigned int __btflo(unsigned int word)
|
||||
{
|
||||
unsigned int ret;
|
||||
asm volatile("bfind.u32 %0, %1;" : "=r"(ret) : "r"(word));
|
||||
return ret;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// qcompare
|
||||
//
|
||||
// Comparison function. Note difference from libc standard in
|
||||
// that we take by reference, not by pointer. I can't figure
|
||||
// out how to get a template-to-pointer specialisation working.
|
||||
// Perhaps it requires a class?
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
__device__ __forceinline__ int qcompare(unsigned &val1, unsigned &val2)
|
||||
{
|
||||
return (val1 > val2) ? 1 : (val1 == val2) ? 0 : -1;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Basic any-N bitonic sort. We sort "len" elements of "indata", starting
|
||||
// from the "offset" elements into the input data array. Note that "outdata"
|
||||
// can safely be the same as "indata" for an in-place sort (we stage through
|
||||
// shared memory).
|
||||
//
|
||||
// We handle non-power-of-2 sizes by padding out to the next largest power of
|
||||
// 2.
|
||||
// This is the fully-generic version, for sorting arbitrary data which does not
|
||||
// have a clear "maximum" value. We track "invalid" entries in a separate array
|
||||
// to make sure that they always sorts as "max value" elements. A template
|
||||
// parameter "OOR" allows specialisation to optimise away the invalid tracking.
|
||||
//
|
||||
// We can do a more specialised version for int/longlong/flat/double, in which
|
||||
// we pad out the array with max-value-of-type elements. That's another
|
||||
// function.
|
||||
//
|
||||
// The last step copies from indata -> outdata... the rest is done in-place.
|
||||
// We use shared memory as temporary storage, which puts an upper limit on
|
||||
// how much data we can sort per block.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
static __device__ __forceinline__ void
|
||||
bitonicsort_kernel(unsigned *indata, unsigned *outdata, unsigned int offset, unsigned int len, cg::thread_block cta)
|
||||
{
|
||||
__shared__ unsigned sortbuf[1024]; // Max of 1024 elements - TODO: make this dynamic
|
||||
|
||||
// First copy data into shared memory.
|
||||
unsigned int inside = (threadIdx.x < len);
|
||||
sortbuf[threadIdx.x] = inside ? indata[threadIdx.x + offset] : 0xffffffffu;
|
||||
cg::sync(cta);
|
||||
|
||||
// Now the sort loops
|
||||
// Here, "k" is the sort level (remember bitonic does a multi-level butterfly
|
||||
// style sort)
|
||||
// and "j" is the partner element in the butterfly.
|
||||
// Two threads each work on one butterfly, because the read/write needs to
|
||||
// happen
|
||||
// simultaneously
|
||||
for (unsigned int k = 2; k <= blockDim.x; k *= 2) // Butterfly stride increments in powers of 2
|
||||
{
|
||||
for (unsigned int j = k >> 1; j > 0; j >>= 1) // Strides also in powers of to, up to <k
|
||||
{
|
||||
unsigned int swap_idx = threadIdx.x ^ j; // Index of element we're compare-and-swapping with
|
||||
unsigned my_elem = sortbuf[threadIdx.x];
|
||||
unsigned swap_elem = sortbuf[swap_idx];
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
// The k'th bit of my threadid (and hence my sort item ID)
|
||||
// determines if we sort ascending or descending.
|
||||
// However, since threads are reading from the top AND the bottom of
|
||||
// the butterfly, if my ID is > swap_idx, then ascending means mine<swap.
|
||||
// Finally, if either my_elem or swap_elem is out of range, then it
|
||||
// ALWAYS acts like it's the largest number.
|
||||
// Confusing? It saves us two writes though.
|
||||
unsigned int ascend = k * (swap_idx < threadIdx.x);
|
||||
unsigned int descend = k * (swap_idx > threadIdx.x);
|
||||
bool swap = false;
|
||||
|
||||
if ((threadIdx.x & k) == ascend) {
|
||||
if (my_elem > swap_elem)
|
||||
swap = true;
|
||||
}
|
||||
|
||||
if ((threadIdx.x & k) == descend) {
|
||||
if (my_elem < swap_elem)
|
||||
swap = true;
|
||||
}
|
||||
|
||||
// If we had to swap, then write my data to the other element's position.
|
||||
// Don't forget to track out-of-range status too!
|
||||
if (swap) {
|
||||
sortbuf[swap_idx] = my_elem;
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
}
|
||||
}
|
||||
|
||||
// Copy the sorted data from shared memory back to the output buffer
|
||||
if (threadIdx.x < len)
|
||||
outdata[threadIdx.x + offset] = sortbuf[threadIdx.x];
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
// This is an emergency-CTA sort, which sorts an arbitrary sized chunk
|
||||
// using a single block. Useful for if qsort runs out of nesting depth.
|
||||
//
|
||||
// Note that bitonic sort needs enough storage to pad up to the nearest
|
||||
// power of 2. This means that the double-buffer is always large enough
|
||||
// (when combined with the main buffer), but we do not get enough space
|
||||
// to keep OOR information.
|
||||
//
|
||||
// This in turn means that this sort does not work with a generic data
|
||||
// type. It must be a directly-comparable (i.e. with max value) type.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
static __device__ __forceinline__ void big_bitonicsort_kernel(unsigned *indata,
|
||||
unsigned *outdata,
|
||||
unsigned *backbuf,
|
||||
unsigned int offset,
|
||||
unsigned int len,
|
||||
cg::thread_block cta)
|
||||
{
|
||||
unsigned int len2 = 1 << (__btflo(len - 1U) + 1); // Round up len to nearest power-of-2
|
||||
|
||||
if (threadIdx.x >= len2)
|
||||
return; // Early out for case where more threads launched than there is
|
||||
// data
|
||||
|
||||
// First, set up our unused values to be the max data type.
|
||||
for (unsigned int i = len; i < len2; i += blockDim.x) {
|
||||
unsigned int index = i + threadIdx.x;
|
||||
|
||||
if (index < len2) {
|
||||
// Must split our index between two buffers
|
||||
if (index < len)
|
||||
indata[index + offset] = 0xffffffffu;
|
||||
else
|
||||
backbuf[index + offset - len] = 0xffffffffu;
|
||||
}
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
// Now the sort loops
|
||||
// Here, "k" is the sort level (remember bitonic does a multi-level butterfly
|
||||
// style sort)
|
||||
// and "j" is the partner element in the butterfly.
|
||||
// Two threads each work on one butterfly, because the read/write needs to
|
||||
// happen
|
||||
// simultaneously
|
||||
for (unsigned int k = 2; k <= len2; k *= 2) // Butterfly stride increments in powers of 2
|
||||
{
|
||||
for (unsigned int j = k >> 1; j > 0; j >>= 1) // Strides also in powers of to, up to <k
|
||||
{
|
||||
for (unsigned int i = 0; i < len2; i += blockDim.x) {
|
||||
unsigned int index = threadIdx.x + i;
|
||||
unsigned int swap_idx = index ^ j; // Index of element we're compare-and-swapping with
|
||||
|
||||
// Only do the swap for index<swap_idx (avoids collision between other
|
||||
// threads)
|
||||
if (swap_idx > index) {
|
||||
unsigned my_elem, swap_elem;
|
||||
|
||||
if (index < len)
|
||||
my_elem = indata[index + offset];
|
||||
else
|
||||
my_elem = backbuf[index + offset - len];
|
||||
|
||||
if (swap_idx < len)
|
||||
swap_elem = indata[swap_idx + offset];
|
||||
else
|
||||
swap_elem = backbuf[swap_idx + offset - len];
|
||||
|
||||
// The k'th bit of my index (and hence my sort item ID)
|
||||
// determines if we sort ascending or descending.
|
||||
// Also, if either my_elem or swap_elem is out of range, then it
|
||||
// ALWAYS acts like it's the largest number.
|
||||
bool swap = false;
|
||||
|
||||
if ((index & k) == 0) {
|
||||
if (my_elem > swap_elem)
|
||||
swap = true;
|
||||
}
|
||||
|
||||
if ((index & k) == k) {
|
||||
if (my_elem < swap_elem)
|
||||
swap = true;
|
||||
}
|
||||
|
||||
// If we had to swap, then write my data to the other element's
|
||||
// position.
|
||||
if (swap) {
|
||||
if (swap_idx < len)
|
||||
indata[swap_idx + offset] = my_elem;
|
||||
else
|
||||
backbuf[swap_idx + offset - len] = my_elem;
|
||||
|
||||
if (index < len)
|
||||
indata[index + offset] = swap_elem;
|
||||
else
|
||||
backbuf[index + offset - len] = swap_elem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cg::sync(cta); // Only need to sync for each "j" pass
|
||||
}
|
||||
}
|
||||
|
||||
// Copy the sorted data from the input to the output buffer, because we sort
|
||||
// in-place
|
||||
if (outdata != indata) {
|
||||
for (unsigned int i = 0; i < len; i += blockDim.x) {
|
||||
unsigned int index = i + threadIdx.x;
|
||||
|
||||
if (index < len)
|
||||
outdata[index + offset] = indata[index + offset];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// KERNELS
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
__global__ void bitonicsort(unsigned *indata, unsigned *outdata, unsigned int offset, unsigned int len)
|
||||
{
|
||||
// Handle to thread block group
|
||||
cg::thread_block cta = cg::this_thread_block();
|
||||
bitonicsort_kernel(indata, outdata, offset, len, cta);
|
||||
}
|
||||
|
||||
__global__ void
|
||||
big_bitonicsort(unsigned *indata, unsigned *outdata, unsigned *backbuf, unsigned int offset, unsigned int len)
|
||||
{
|
||||
// Handle to thread block group
|
||||
cg::thread_block cta = cg::this_thread_block();
|
||||
big_bitonicsort_kernel(indata, outdata, backbuf, offset, len, cta);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
77
cpp/3_CUDA_Features/cdpAdvancedQuicksort/cdpQuicksort.h
Normal file
77
cpp/3_CUDA_Features/cdpAdvancedQuicksort/cdpQuicksort.h
Normal file
@@ -0,0 +1,77 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// Definitions for GPU quicksort
|
||||
|
||||
#ifndef QUICKSORT_H
|
||||
#define QUICKSORT_H
|
||||
|
||||
#define QSORT_BLOCKSIZE_SHIFT 9
|
||||
#define QSORT_BLOCKSIZE (1 << QSORT_BLOCKSIZE_SHIFT)
|
||||
#define BITONICSORT_LEN 1024 // Must be power of 2!
|
||||
#define QSORT_MAXDEPTH 16 // Will force final bitonic stage at depth QSORT_MAXDEPTH+1
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// The algorithm uses several variables updated by using atomic operations.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
typedef struct __align__(128) qsortAtomicData_t
|
||||
{
|
||||
volatile unsigned int lt_offset; // Current output offset for <pivot
|
||||
volatile unsigned int gt_offset; // Current output offset for >pivot
|
||||
volatile unsigned int sorted_count; // Total count sorted, for deciding when
|
||||
// to launch next wave
|
||||
volatile unsigned int index; // Ringbuf tracking index. Can be ignored if not using ringbuf.
|
||||
} qsortAtomicData;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// A ring-buffer for rapid stack allocation
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
typedef struct qsortRingbuf_t
|
||||
{
|
||||
volatile unsigned int head; // Head pointer - we allocate from here
|
||||
volatile unsigned int tail; // Tail pointer - indicates last still-in-use element
|
||||
volatile unsigned int count; // Total count allocated
|
||||
volatile unsigned int max; // Max index allocated
|
||||
unsigned int stacksize; // Wrap-around size of buffer (must be power of 2)
|
||||
volatile void *stackbase; // Pointer to the stack we're allocating from
|
||||
} qsortRingbuf;
|
||||
|
||||
// Stack elem count must be power of 2!
|
||||
#define QSORT_STACK_ELEMS 1 * 1024 * 1024 // One million stack elements is a HUGE number.
|
||||
|
||||
__global__ void qsort_warp(unsigned *indata,
|
||||
unsigned *outdata,
|
||||
unsigned int len,
|
||||
qsortAtomicData *atomicData,
|
||||
qsortRingbuf *ringbuf,
|
||||
unsigned int source_is_indata,
|
||||
unsigned int depth);
|
||||
__global__ void bitonicsort(unsigned *indata, unsigned *outdata, unsigned int offset, unsigned int len);
|
||||
__global__ void
|
||||
big_bitonicsort(unsigned *indata, unsigned *outdata, unsigned *backbuf, unsigned int offset, unsigned int len);
|
||||
|
||||
#endif // QUICKSORT_H
|
||||
18
cpp/3_CUDA_Features/cdpBezierTessellation/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/cdpBezierTessellation/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/cdpBezierTessellation/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/cdpBezierTessellation/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
205
cpp/3_CUDA_Features/cdpBezierTessellation/BezierLineCDP.cu
Normal file
205
cpp/3_CUDA_Features/cdpBezierTessellation/BezierLineCDP.cu
Normal file
@@ -0,0 +1,205 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cuda_runtime_api.h>
|
||||
#include <helper_cuda.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
__forceinline__ __device__ float2 operator+(float2 a, float2 b)
|
||||
{
|
||||
float2 c;
|
||||
c.x = a.x + b.x;
|
||||
c.y = a.y + b.y;
|
||||
return c;
|
||||
}
|
||||
|
||||
__forceinline__ __device__ float2 operator-(float2 a, float2 b)
|
||||
{
|
||||
float2 c;
|
||||
c.x = a.x - b.x;
|
||||
c.y = a.y - b.y;
|
||||
return c;
|
||||
}
|
||||
|
||||
__forceinline__ __device__ float2 operator*(float a, float2 b)
|
||||
{
|
||||
float2 c;
|
||||
c.x = a * b.x;
|
||||
c.y = a * b.y;
|
||||
return c;
|
||||
}
|
||||
|
||||
__forceinline__ __device__ float length(float2 a) { return sqrtf(a.x * a.x + a.y * a.y); }
|
||||
|
||||
#define MAX_TESSELLATION 32
|
||||
struct BezierLine
|
||||
{
|
||||
float2 CP[3];
|
||||
float2 *vertexPos;
|
||||
int nVertices;
|
||||
};
|
||||
|
||||
__global__ void computeBezierLinePositions(int lidx, BezierLine *bLines, int nTessPoints)
|
||||
{
|
||||
int idx = threadIdx.x + blockDim.x * blockIdx.x;
|
||||
|
||||
if (idx < nTessPoints) {
|
||||
float u = (float)idx / (float)(nTessPoints - 1);
|
||||
float omu = 1.0f - u;
|
||||
|
||||
float B3u[3];
|
||||
|
||||
B3u[0] = omu * omu;
|
||||
B3u[1] = 2.0f * u * omu;
|
||||
B3u[2] = u * u;
|
||||
|
||||
float2 position = {0, 0};
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
position = position + B3u[i] * bLines[lidx].CP[i];
|
||||
}
|
||||
|
||||
bLines[lidx].vertexPos[idx] = position;
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void computeBezierLinesCDP(BezierLine *bLines, int nLines)
|
||||
{
|
||||
int lidx = threadIdx.x + blockDim.x * blockIdx.x;
|
||||
|
||||
if (lidx < nLines) {
|
||||
float curvature = length(bLines[lidx].CP[1] - 0.5f * (bLines[lidx].CP[0] + bLines[lidx].CP[2]))
|
||||
/ length(bLines[lidx].CP[2] - bLines[lidx].CP[0]);
|
||||
int nTessPoints = min(max((int)(curvature * 16.0f), 4), MAX_TESSELLATION);
|
||||
|
||||
if (bLines[lidx].vertexPos == NULL) {
|
||||
bLines[lidx].nVertices = nTessPoints;
|
||||
cudaMalloc((void **)&bLines[lidx].vertexPos, nTessPoints * sizeof(float2));
|
||||
}
|
||||
|
||||
computeBezierLinePositions<<<ceilf((float)bLines[lidx].nVertices / 32.0f), 32>>>(
|
||||
lidx, bLines, bLines[lidx].nVertices);
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void freeVertexMem(BezierLine *bLines, int nLines)
|
||||
{
|
||||
int lidx = threadIdx.x + blockDim.x * blockIdx.x;
|
||||
|
||||
if (lidx < nLines)
|
||||
cudaFree(bLines[lidx].vertexPos);
|
||||
}
|
||||
|
||||
unsigned int checkCapableSM35Device(int argc, char **argv)
|
||||
{
|
||||
// Get device properties
|
||||
cudaDeviceProp properties;
|
||||
int device_count = 0, device = -1;
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "device")) {
|
||||
device = getCmdLineArgumentInt(argc, (const char **)argv, "device");
|
||||
|
||||
cudaDeviceProp properties;
|
||||
checkCudaErrors(cudaGetDeviceProperties(&properties, device));
|
||||
|
||||
if (properties.major > 3 || (properties.major == 3 && properties.minor >= 5)) {
|
||||
printf("Running on GPU %d (%s)\n", device, properties.name);
|
||||
}
|
||||
else {
|
||||
printf("cdpBezierTessellation requires GPU devices with compute SM 3.5 or "
|
||||
"higher.");
|
||||
printf("Current GPU device has compute SM %d.%d. Exiting...\n", properties.major, properties.minor);
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
else {
|
||||
checkCudaErrors(cudaGetDeviceCount(&device_count));
|
||||
|
||||
for (int i = 0; i < device_count; ++i) {
|
||||
checkCudaErrors(cudaGetDeviceProperties(&properties, i));
|
||||
|
||||
if (properties.major > 3 || (properties.major == 3 && properties.minor >= 5)) {
|
||||
device = i;
|
||||
printf("Running on GPU %d (%s)\n", i, properties.name);
|
||||
break;
|
||||
}
|
||||
|
||||
printf("GPU %d %s does not support CUDA Dynamic Parallelism\n", i, properties.name);
|
||||
}
|
||||
}
|
||||
if (device == -1) {
|
||||
fprintf(stderr,
|
||||
"cdpBezierTessellation requires GPU devices with compute SM 3.5 or "
|
||||
"higher. Exiting...\n");
|
||||
return EXIT_WAIVED;
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
#define N_LINES 256
|
||||
#define BLOCK_DIM 64
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
BezierLine *bLines_h = new BezierLine[N_LINES];
|
||||
|
||||
float2 last = {0, 0};
|
||||
|
||||
for (int i = 0; i < N_LINES; i++) {
|
||||
bLines_h[i].CP[0] = last;
|
||||
|
||||
for (int j = 1; j < 3; j++) {
|
||||
bLines_h[i].CP[j].x = (float)rand() / (float)RAND_MAX;
|
||||
bLines_h[i].CP[j].y = (float)rand() / (float)RAND_MAX;
|
||||
}
|
||||
|
||||
last = bLines_h[i].CP[2];
|
||||
bLines_h[i].vertexPos = NULL;
|
||||
bLines_h[i].nVertices = 0;
|
||||
}
|
||||
|
||||
unsigned int sm35Ret = checkCapableSM35Device(argc, argv);
|
||||
if (sm35Ret != EXIT_SUCCESS) {
|
||||
exit(sm35Ret);
|
||||
}
|
||||
|
||||
BezierLine *bLines_d;
|
||||
checkCudaErrors(cudaMalloc((void **)&bLines_d, N_LINES * sizeof(BezierLine)));
|
||||
checkCudaErrors(cudaMemcpy(bLines_d, bLines_h, N_LINES * sizeof(BezierLine), cudaMemcpyHostToDevice));
|
||||
printf("Computing Bezier Lines (CUDA Dynamic Parallelism Version) ... ");
|
||||
computeBezierLinesCDP<<<(unsigned int)ceil((float)N_LINES / (float)BLOCK_DIM), BLOCK_DIM>>>(bLines_d, N_LINES);
|
||||
printf("Done!\n");
|
||||
|
||||
// Do something to draw the lines here
|
||||
|
||||
freeVertexMem<<<(unsigned int)ceil((float)N_LINES / (float)BLOCK_DIM), BLOCK_DIM>>>(bLines_d, N_LINES);
|
||||
checkCudaErrors(cudaFree(bLines_d));
|
||||
delete[] bLines_h;
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
43
cpp/3_CUDA_Features/cdpBezierTessellation/CMakeLists.txt
Normal file
43
cpp/3_CUDA_Features/cdpBezierTessellation/CMakeLists.txt
Normal file
@@ -0,0 +1,43 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(cdpBezierTessellation LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# The aarch64/sbsa_aarch64 CUDA toolkit are support on Tegra since 13.0, so need to check which version of the toolkit is installed
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-linux" _aarch64_linux_ctk)
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-qnx" _aarch64_qnx_ctk)
|
||||
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" AND (NOT _aarch64_linux_ctk EQUAL -1 OR NOT _aarch64_qnx_ctk EQUAL -1))
|
||||
set(CMAKE_CUDA_ARCHITECTURES 87 110)
|
||||
else()
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 89 90 100 110 120)
|
||||
endif()
|
||||
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for cdpBezierTessellation
|
||||
add_executable(cdpBezierTessellation BezierLineCDP.cu)
|
||||
|
||||
target_compile_options(cdpBezierTessellation PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(cdpBezierTessellation PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(cdpBezierTessellation PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
34
cpp/3_CUDA_Features/cdpBezierTessellation/README.md
Normal file
34
cpp/3_CUDA_Features/cdpBezierTessellation/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# cdpBezierTessellation - Bezier Line Tessellation (CUDA Dynamic Parallelism)
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates bezier tessellation of lines implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Dynamic Parallelism
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaFree, cudaGetDeviceCount, cudaMalloc, cudaGetDeviceProperties
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[CDP](../../../README.md#cuda-dynamic-parallellism)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
18
cpp/3_CUDA_Features/cdpQuadtree/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/cdpQuadtree/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/cdpQuadtree/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/cdpQuadtree/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
43
cpp/3_CUDA_Features/cdpQuadtree/CMakeLists.txt
Normal file
43
cpp/3_CUDA_Features/cdpQuadtree/CMakeLists.txt
Normal file
@@ -0,0 +1,43 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(cdpQuadtree LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# The aarch64/sbsa_aarch64 CUDA toolkit are support on Tegra since 13.0, so need to check which version of the toolkit is installed
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-linux" _aarch64_linux_ctk)
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-qnx" _aarch64_qnx_ctk)
|
||||
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" AND (NOT _aarch64_linux_ctk EQUAL -1 OR NOT _aarch64_qnx_ctk EQUAL -1))
|
||||
set(CMAKE_CUDA_ARCHITECTURES 87 110)
|
||||
else()
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 89 90 100 110 120)
|
||||
endif()
|
||||
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for cdpQuadtree
|
||||
add_executable(cdpQuadtree cdpQuadtree.cu)
|
||||
|
||||
target_compile_options(cdpQuadtree PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(cdpQuadtree PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(cdpQuadtree PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
34
cpp/3_CUDA_Features/cdpQuadtree/README.md
Normal file
34
cpp/3_CUDA_Features/cdpQuadtree/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# cdpQuadtree - Quad Tree (CUDA Dynamic Parallelism)
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates Quad Trees implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Cooperative Groups, CUDA Dynamic Parallelism
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaFree, cudaGetLastError, cudaDeviceSetLimit, cudaMalloc, cudaGetDeviceProperties
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[CDP](../../../README.md#cuda-dynamic-parallellism)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
734
cpp/3_CUDA_Features/cdpQuadtree/cdpQuadtree.cu
Normal file
734
cpp/3_CUDA_Features/cdpQuadtree/cdpQuadtree.cu
Normal file
@@ -0,0 +1,734 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cooperative_groups.h>
|
||||
#include <thrust/device_vector.h>
|
||||
#include <thrust/host_vector.h>
|
||||
#include <thrust/random.h>
|
||||
|
||||
// for cuda::std::tuple
|
||||
#include <cuda/std/tuple>
|
||||
|
||||
namespace cg = cooperative_groups;
|
||||
#include <helper_cuda.h>
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// A structure of 2D points (structure of arrays).
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
class Points
|
||||
{
|
||||
float *m_x;
|
||||
float *m_y;
|
||||
|
||||
public:
|
||||
// Constructor.
|
||||
__host__ __device__ Points()
|
||||
: m_x(NULL)
|
||||
, m_y(NULL)
|
||||
{
|
||||
}
|
||||
|
||||
// Constructor.
|
||||
__host__ __device__ Points(float *x, float *y)
|
||||
: m_x(x)
|
||||
, m_y(y)
|
||||
{
|
||||
}
|
||||
|
||||
// Get a point.
|
||||
__host__ __device__ __forceinline__ float2 get_point(int idx) const { return make_float2(m_x[idx], m_y[idx]); }
|
||||
|
||||
// Set a point.
|
||||
__host__ __device__ __forceinline__ void set_point(int idx, const float2 &p)
|
||||
{
|
||||
m_x[idx] = p.x;
|
||||
m_y[idx] = p.y;
|
||||
}
|
||||
|
||||
// Set the pointers.
|
||||
__host__ __device__ __forceinline__ void set(float *x, float *y)
|
||||
{
|
||||
m_x = x;
|
||||
m_y = y;
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// A 2D bounding box
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
class Bounding_box
|
||||
{
|
||||
// Extreme points of the bounding box.
|
||||
float2 m_p_min;
|
||||
float2 m_p_max;
|
||||
|
||||
public:
|
||||
// Constructor. Create a unit box.
|
||||
__host__ __device__ Bounding_box()
|
||||
{
|
||||
m_p_min = make_float2(0.0f, 0.0f);
|
||||
m_p_max = make_float2(1.0f, 1.0f);
|
||||
}
|
||||
|
||||
// Compute the center of the bounding-box.
|
||||
__host__ __device__ void compute_center(float2 ¢er) const
|
||||
{
|
||||
center.x = 0.5f * (m_p_min.x + m_p_max.x);
|
||||
center.y = 0.5f * (m_p_min.y + m_p_max.y);
|
||||
}
|
||||
|
||||
// The points of the box.
|
||||
__host__ __device__ __forceinline__ const float2 &get_max() const { return m_p_max; }
|
||||
|
||||
__host__ __device__ __forceinline__ const float2 &get_min() const { return m_p_min; }
|
||||
|
||||
// Does a box contain a point.
|
||||
__host__ __device__ bool contains(const float2 &p) const
|
||||
{
|
||||
return p.x >= m_p_min.x && p.x < m_p_max.x && p.y >= m_p_min.y && p.y < m_p_max.y;
|
||||
}
|
||||
|
||||
// Define the bounding box.
|
||||
__host__ __device__ void set(float min_x, float min_y, float max_x, float max_y)
|
||||
{
|
||||
m_p_min.x = min_x;
|
||||
m_p_min.y = min_y;
|
||||
m_p_max.x = max_x;
|
||||
m_p_max.y = max_y;
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// A node of a quadree.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
class Quadtree_node
|
||||
{
|
||||
// The identifier of the node.
|
||||
int m_id;
|
||||
// The bounding box of the tree.
|
||||
Bounding_box m_bounding_box;
|
||||
// The range of points.
|
||||
int m_begin, m_end;
|
||||
|
||||
public:
|
||||
// Constructor.
|
||||
__host__ __device__ Quadtree_node()
|
||||
: m_id(0)
|
||||
, m_begin(0)
|
||||
, m_end(0)
|
||||
{
|
||||
}
|
||||
|
||||
// The ID of a node at its level.
|
||||
__host__ __device__ int id() const { return m_id; }
|
||||
|
||||
// The ID of a node at its level.
|
||||
__host__ __device__ void set_id(int new_id) { m_id = new_id; }
|
||||
|
||||
// The bounding box.
|
||||
__host__ __device__ __forceinline__ const Bounding_box &bounding_box() const { return m_bounding_box; }
|
||||
|
||||
// Set the bounding box.
|
||||
__host__ __device__ __forceinline__ void set_bounding_box(float min_x, float min_y, float max_x, float max_y)
|
||||
{
|
||||
m_bounding_box.set(min_x, min_y, max_x, max_y);
|
||||
}
|
||||
|
||||
// The number of points in the tree.
|
||||
__host__ __device__ __forceinline__ int num_points() const { return m_end - m_begin; }
|
||||
|
||||
// The range of points in the tree.
|
||||
__host__ __device__ __forceinline__ int points_begin() const { return m_begin; }
|
||||
|
||||
__host__ __device__ __forceinline__ int points_end() const { return m_end; }
|
||||
|
||||
// Define the range for that node.
|
||||
__host__ __device__ __forceinline__ void set_range(int begin, int end)
|
||||
{
|
||||
m_begin = begin;
|
||||
m_end = end;
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Algorithm parameters.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
struct Parameters
|
||||
{
|
||||
// Choose the right set of points to use as in/out.
|
||||
int point_selector;
|
||||
// The number of nodes at a given level (2^k for level k).
|
||||
int num_nodes_at_this_level;
|
||||
// The recursion depth.
|
||||
int depth;
|
||||
// The max value for depth.
|
||||
const int max_depth;
|
||||
// The minimum number of points in a node to stop recursion.
|
||||
const int min_points_per_node;
|
||||
|
||||
// Constructor set to default values.
|
||||
__host__ __device__ Parameters(int max_depth, int min_points_per_node)
|
||||
: point_selector(0)
|
||||
, num_nodes_at_this_level(1)
|
||||
, depth(0)
|
||||
, max_depth(max_depth)
|
||||
, min_points_per_node(min_points_per_node)
|
||||
{
|
||||
}
|
||||
|
||||
// Copy constructor. Changes the values for next iteration.
|
||||
__host__ __device__ Parameters(const Parameters ¶ms, bool)
|
||||
: point_selector((params.point_selector + 1) % 2)
|
||||
, num_nodes_at_this_level(4 * params.num_nodes_at_this_level)
|
||||
, depth(params.depth + 1)
|
||||
, max_depth(params.max_depth)
|
||||
, min_points_per_node(params.min_points_per_node)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Build a quadtree on the GPU. Use CUDA Dynamic Parallelism.
|
||||
//
|
||||
// The algorithm works as follows. The host (CPU) launches one block of
|
||||
// NUM_THREADS_PER_BLOCK threads. That block will do the following steps:
|
||||
//
|
||||
// 1- Check the number of points and its depth.
|
||||
//
|
||||
// We impose a maximum depth to the tree and a minimum number of points per
|
||||
// node. If the maximum depth is exceeded or the minimum number of points is
|
||||
// reached. The threads in the block exit.
|
||||
//
|
||||
// Before exiting, they perform a buffer swap if it is needed. Indeed, the
|
||||
// algorithm uses two buffers to permute the points and make sure they are
|
||||
// properly distributed in the quadtree. By design we want all points to be
|
||||
// in the first buffer of points at the end of the algorithm. It is the reason
|
||||
// why we may have to swap the buffer before leavin (if the points are in the
|
||||
// 2nd buffer).
|
||||
//
|
||||
// 2- Count the number of points in each child.
|
||||
//
|
||||
// If the depth is not too high and the number of points is sufficient, the
|
||||
// block has to dispatch the points into four geometrical buckets: Its
|
||||
// children. For that purpose, we compute the center of the bounding box and
|
||||
// count the number of points in each quadrant.
|
||||
//
|
||||
// The set of points is divided into sections. Each section is given to a
|
||||
// warp of threads (32 threads). Warps use __ballot and __popc intrinsics
|
||||
// to count the points. See the Programming Guide for more information about
|
||||
// those functions.
|
||||
//
|
||||
// 3- Scan the warps' results to know the "global" numbers.
|
||||
//
|
||||
// Warps work independently from each other. At the end, each warp knows the
|
||||
// number of points in its section. To know the numbers for the block, the
|
||||
// block has to run a scan/reduce at the block level. It's a traditional
|
||||
// approach. The implementation in that sample is not as optimized as what
|
||||
// could be found in fast radix sorts, for example, but it relies on the same
|
||||
// idea.
|
||||
//
|
||||
// 4- Move points.
|
||||
//
|
||||
// Now that the block knows how many points go in each of its 4 children, it
|
||||
// remains to dispatch the points. It is straightforward.
|
||||
//
|
||||
// 5- Launch new blocks.
|
||||
//
|
||||
// The block launches four new blocks: One per children. Each of the four blocks
|
||||
// will apply the same algorithm.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
template <int NUM_THREADS_PER_BLOCK>
|
||||
__global__ void build_quadtree_kernel(Quadtree_node *nodes, Points *points, Parameters params)
|
||||
{
|
||||
// Handle to thread block group
|
||||
cg::thread_block cta = cg::this_thread_block();
|
||||
// The number of warps in a block.
|
||||
const int NUM_WARPS_PER_BLOCK = NUM_THREADS_PER_BLOCK / warpSize;
|
||||
|
||||
// Shared memory to store the number of points.
|
||||
extern __shared__ int smem[];
|
||||
|
||||
// s_num_pts[4][NUM_WARPS_PER_BLOCK];
|
||||
// Addresses of shared memory.
|
||||
volatile int *s_num_pts[4];
|
||||
|
||||
for (int i = 0; i < 4; ++i)
|
||||
s_num_pts[i] = (volatile int *)&smem[i * NUM_WARPS_PER_BLOCK];
|
||||
|
||||
// Compute the coordinates of the threads in the block.
|
||||
const int warp_id = threadIdx.x / warpSize;
|
||||
const int lane_id = threadIdx.x % warpSize;
|
||||
|
||||
// Mask for compaction.
|
||||
// Same as: asm( "mov.u32 %0, %%lanemask_lt;" : "=r"(lane_mask_lt) );
|
||||
int lane_mask_lt = (1 << lane_id) - 1;
|
||||
|
||||
// The current node.
|
||||
Quadtree_node &node = nodes[blockIdx.x];
|
||||
|
||||
// The number of points in the node.
|
||||
int num_points = node.num_points();
|
||||
|
||||
float2 center;
|
||||
int range_begin, range_end;
|
||||
int warp_cnts[4] = {0, 0, 0, 0};
|
||||
//
|
||||
// 1- Check the number of points and its depth.
|
||||
//
|
||||
|
||||
// Stop the recursion here. Make sure points[0] contains all the points.
|
||||
if (params.depth >= params.max_depth || num_points <= params.min_points_per_node) {
|
||||
if (params.point_selector == 1) {
|
||||
int it = node.points_begin(), end = node.points_end();
|
||||
|
||||
for (it += threadIdx.x; it < end; it += NUM_THREADS_PER_BLOCK)
|
||||
if (it < end)
|
||||
points[0].set_point(it, points[1].get_point(it));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Compute the center of the bounding box of the points.
|
||||
const Bounding_box &bbox = node.bounding_box();
|
||||
|
||||
bbox.compute_center(center);
|
||||
|
||||
// Find how many points to give to each warp.
|
||||
int num_points_per_warp = max(warpSize, (num_points + NUM_WARPS_PER_BLOCK - 1) / NUM_WARPS_PER_BLOCK);
|
||||
|
||||
// Each warp of threads will compute the number of points to move to each
|
||||
// quadrant.
|
||||
range_begin = node.points_begin() + warp_id * num_points_per_warp;
|
||||
range_end = min(range_begin + num_points_per_warp, node.points_end());
|
||||
|
||||
//
|
||||
// 2- Count the number of points in each child.
|
||||
//
|
||||
|
||||
// Input points.
|
||||
const Points &in_points = points[params.point_selector];
|
||||
|
||||
cg::thread_block_tile<32> tile32 = cg::tiled_partition<32>(cta);
|
||||
// Compute the number of points.
|
||||
for (int range_it = range_begin + tile32.thread_rank(); tile32.any(range_it < range_end); range_it += warpSize) {
|
||||
// Is it still an active thread?
|
||||
bool is_active = range_it < range_end;
|
||||
|
||||
// Load the coordinates of the point.
|
||||
float2 p = is_active ? in_points.get_point(range_it) : make_float2(0.0f, 0.0f);
|
||||
|
||||
// Count top-left points.
|
||||
int num_pts = __popc(tile32.ballot(is_active && p.x < center.x && p.y >= center.y));
|
||||
warp_cnts[0] += tile32.shfl(num_pts, 0);
|
||||
|
||||
// Count top-right points.
|
||||
num_pts = __popc(tile32.ballot(is_active && p.x >= center.x && p.y >= center.y));
|
||||
warp_cnts[1] += tile32.shfl(num_pts, 0);
|
||||
|
||||
// Count bottom-left points.
|
||||
num_pts = __popc(tile32.ballot(is_active && p.x < center.x && p.y < center.y));
|
||||
warp_cnts[2] += tile32.shfl(num_pts, 0);
|
||||
|
||||
// Count bottom-right points.
|
||||
num_pts = __popc(tile32.ballot(is_active && p.x >= center.x && p.y < center.y));
|
||||
warp_cnts[3] += tile32.shfl(num_pts, 0);
|
||||
}
|
||||
|
||||
if (tile32.thread_rank() == 0) {
|
||||
s_num_pts[0][warp_id] = warp_cnts[0];
|
||||
s_num_pts[1][warp_id] = warp_cnts[1];
|
||||
s_num_pts[2][warp_id] = warp_cnts[2];
|
||||
s_num_pts[3][warp_id] = warp_cnts[3];
|
||||
}
|
||||
|
||||
// Make sure warps have finished counting.
|
||||
cg::sync(cta);
|
||||
|
||||
//
|
||||
// 3- Scan the warps' results to know the "global" numbers.
|
||||
//
|
||||
|
||||
// First 4 warps scan the numbers of points per child (inclusive scan).
|
||||
if (warp_id < 4) {
|
||||
int num_pts = tile32.thread_rank() < NUM_WARPS_PER_BLOCK ? s_num_pts[warp_id][tile32.thread_rank()] : 0;
|
||||
#pragma unroll
|
||||
|
||||
for (int offset = 1; offset < NUM_WARPS_PER_BLOCK; offset *= 2) {
|
||||
int n = tile32.shfl_up(num_pts, offset);
|
||||
|
||||
if (tile32.thread_rank() >= offset)
|
||||
num_pts += n;
|
||||
}
|
||||
|
||||
if (tile32.thread_rank() < NUM_WARPS_PER_BLOCK)
|
||||
s_num_pts[warp_id][tile32.thread_rank()] = num_pts;
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
// Compute global offsets.
|
||||
if (warp_id == 0) {
|
||||
int sum = s_num_pts[0][NUM_WARPS_PER_BLOCK - 1];
|
||||
|
||||
for (int row = 1; row < 4; ++row) {
|
||||
int tmp = s_num_pts[row][NUM_WARPS_PER_BLOCK - 1];
|
||||
cg::sync(tile32);
|
||||
|
||||
if (tile32.thread_rank() < NUM_WARPS_PER_BLOCK)
|
||||
s_num_pts[row][tile32.thread_rank()] += sum;
|
||||
|
||||
cg::sync(tile32);
|
||||
sum += tmp;
|
||||
}
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
// Make the scan exclusive.
|
||||
int val = 0;
|
||||
if (threadIdx.x < 4 * NUM_WARPS_PER_BLOCK) {
|
||||
val = threadIdx.x == 0 ? 0 : smem[threadIdx.x - 1];
|
||||
val += node.points_begin();
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
if (threadIdx.x < 4 * NUM_WARPS_PER_BLOCK) {
|
||||
smem[threadIdx.x] = val;
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
//
|
||||
// 4- Move points.
|
||||
//
|
||||
if (!(params.depth >= params.max_depth || num_points <= params.min_points_per_node)) {
|
||||
// Output points.
|
||||
Points &out_points = points[(params.point_selector + 1) % 2];
|
||||
|
||||
warp_cnts[0] = s_num_pts[0][warp_id];
|
||||
warp_cnts[1] = s_num_pts[1][warp_id];
|
||||
warp_cnts[2] = s_num_pts[2][warp_id];
|
||||
warp_cnts[3] = s_num_pts[3][warp_id];
|
||||
|
||||
const Points &in_points = points[params.point_selector];
|
||||
// Reorder points.
|
||||
for (int range_it = range_begin + tile32.thread_rank(); tile32.any(range_it < range_end);
|
||||
range_it += warpSize) {
|
||||
// Is it still an active thread?
|
||||
bool is_active = range_it < range_end;
|
||||
|
||||
// Load the coordinates of the point.
|
||||
float2 p = is_active ? in_points.get_point(range_it) : make_float2(0.0f, 0.0f);
|
||||
|
||||
// Count top-left points.
|
||||
bool pred = is_active && p.x < center.x && p.y >= center.y;
|
||||
int vote = tile32.ballot(pred);
|
||||
int dest = warp_cnts[0] + __popc(vote & lane_mask_lt);
|
||||
|
||||
if (pred)
|
||||
out_points.set_point(dest, p);
|
||||
|
||||
warp_cnts[0] += tile32.shfl(__popc(vote), 0);
|
||||
|
||||
// Count top-right points.
|
||||
pred = is_active && p.x >= center.x && p.y >= center.y;
|
||||
vote = tile32.ballot(pred);
|
||||
dest = warp_cnts[1] + __popc(vote & lane_mask_lt);
|
||||
|
||||
if (pred)
|
||||
out_points.set_point(dest, p);
|
||||
|
||||
warp_cnts[1] += tile32.shfl(__popc(vote), 0);
|
||||
|
||||
// Count bottom-left points.
|
||||
pred = is_active && p.x < center.x && p.y < center.y;
|
||||
vote = tile32.ballot(pred);
|
||||
dest = warp_cnts[2] + __popc(vote & lane_mask_lt);
|
||||
|
||||
if (pred)
|
||||
out_points.set_point(dest, p);
|
||||
|
||||
warp_cnts[2] += tile32.shfl(__popc(vote), 0);
|
||||
|
||||
// Count bottom-right points.
|
||||
pred = is_active && p.x >= center.x && p.y < center.y;
|
||||
vote = tile32.ballot(pred);
|
||||
dest = warp_cnts[3] + __popc(vote & lane_mask_lt);
|
||||
|
||||
if (pred)
|
||||
out_points.set_point(dest, p);
|
||||
|
||||
warp_cnts[3] += tile32.shfl(__popc(vote), 0);
|
||||
}
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
if (tile32.thread_rank() == 0) {
|
||||
s_num_pts[0][warp_id] = warp_cnts[0];
|
||||
s_num_pts[1][warp_id] = warp_cnts[1];
|
||||
s_num_pts[2][warp_id] = warp_cnts[2];
|
||||
s_num_pts[3][warp_id] = warp_cnts[3];
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
//
|
||||
// 5- Launch new blocks.
|
||||
//
|
||||
if (!(params.depth >= params.max_depth || num_points <= params.min_points_per_node)) {
|
||||
// The last thread launches new blocks.
|
||||
if (threadIdx.x == NUM_THREADS_PER_BLOCK - 1) {
|
||||
// The children.
|
||||
Quadtree_node *children = &nodes[params.num_nodes_at_this_level - (node.id() & ~3)];
|
||||
|
||||
// The offsets of the children at their level.
|
||||
int child_offset = 4 * node.id();
|
||||
|
||||
// Set IDs.
|
||||
children[child_offset + 0].set_id(4 * node.id() + 0);
|
||||
children[child_offset + 1].set_id(4 * node.id() + 1);
|
||||
children[child_offset + 2].set_id(4 * node.id() + 2);
|
||||
children[child_offset + 3].set_id(4 * node.id() + 3);
|
||||
|
||||
const Bounding_box &bbox = node.bounding_box();
|
||||
// Points of the bounding-box.
|
||||
const float2 &p_min = bbox.get_min();
|
||||
const float2 &p_max = bbox.get_max();
|
||||
|
||||
// Set the bounding boxes of the children.
|
||||
children[child_offset + 0].set_bounding_box(p_min.x, center.y, center.x,
|
||||
p_max.y); // Top-left.
|
||||
children[child_offset + 1].set_bounding_box(center.x, center.y, p_max.x,
|
||||
p_max.y); // Top-right.
|
||||
children[child_offset + 2].set_bounding_box(p_min.x, p_min.y, center.x,
|
||||
center.y); // Bottom-left.
|
||||
children[child_offset + 3].set_bounding_box(center.x, p_min.y, p_max.x,
|
||||
center.y); // Bottom-right.
|
||||
|
||||
// Set the ranges of the children.
|
||||
|
||||
children[child_offset + 0].set_range(node.points_begin(), s_num_pts[0][warp_id]);
|
||||
children[child_offset + 1].set_range(s_num_pts[0][warp_id], s_num_pts[1][warp_id]);
|
||||
children[child_offset + 2].set_range(s_num_pts[1][warp_id], s_num_pts[2][warp_id]);
|
||||
children[child_offset + 3].set_range(s_num_pts[2][warp_id], s_num_pts[3][warp_id]);
|
||||
|
||||
// Launch 4 children.
|
||||
build_quadtree_kernel<NUM_THREADS_PER_BLOCK>
|
||||
<<<4, NUM_THREADS_PER_BLOCK, 4 * NUM_WARPS_PER_BLOCK * sizeof(int)>>>(
|
||||
&children[child_offset], points, Parameters(params, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Make sure a Quadtree is properly defined.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
bool check_quadtree(const Quadtree_node *nodes, int idx, int num_pts, Points *pts, Parameters params)
|
||||
{
|
||||
const Quadtree_node &node = nodes[idx];
|
||||
int num_points = node.num_points();
|
||||
|
||||
if (!(params.depth == params.max_depth || num_points <= params.min_points_per_node)) {
|
||||
int num_points_in_children = 0;
|
||||
|
||||
num_points_in_children += nodes[params.num_nodes_at_this_level + 4 * idx + 0].num_points();
|
||||
num_points_in_children += nodes[params.num_nodes_at_this_level + 4 * idx + 1].num_points();
|
||||
num_points_in_children += nodes[params.num_nodes_at_this_level + 4 * idx + 2].num_points();
|
||||
num_points_in_children += nodes[params.num_nodes_at_this_level + 4 * idx + 3].num_points();
|
||||
|
||||
if (num_points_in_children != node.num_points())
|
||||
return false;
|
||||
|
||||
return check_quadtree(
|
||||
&nodes[params.num_nodes_at_this_level], 4 * idx + 0, num_pts, pts, Parameters(params, true))
|
||||
&& check_quadtree(
|
||||
&nodes[params.num_nodes_at_this_level], 4 * idx + 1, num_pts, pts, Parameters(params, true))
|
||||
&& check_quadtree(
|
||||
&nodes[params.num_nodes_at_this_level], 4 * idx + 2, num_pts, pts, Parameters(params, true))
|
||||
&& check_quadtree(
|
||||
&nodes[params.num_nodes_at_this_level], 4 * idx + 3, num_pts, pts, Parameters(params, true));
|
||||
}
|
||||
|
||||
const Bounding_box &bbox = node.bounding_box();
|
||||
|
||||
for (int it = node.points_begin(); it < node.points_end(); ++it) {
|
||||
if (it >= num_pts)
|
||||
return false;
|
||||
|
||||
float2 p = pts->get_point(it);
|
||||
|
||||
if (!bbox.contains(p))
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Parallel random number generator.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
struct Random_generator
|
||||
{
|
||||
int count;
|
||||
|
||||
__host__ __device__ Random_generator()
|
||||
: count(0)
|
||||
{
|
||||
}
|
||||
__host__ __device__ unsigned int hash(unsigned int a)
|
||||
{
|
||||
a = (a + 0x7ed55d16) + (a << 12);
|
||||
a = (a ^ 0xc761c23c) ^ (a >> 19);
|
||||
a = (a + 0x165667b1) + (a << 5);
|
||||
a = (a + 0xd3a2646c) ^ (a << 9);
|
||||
a = (a + 0xfd7046c5) + (a << 3);
|
||||
a = (a ^ 0xb55a4f09) ^ (a >> 16);
|
||||
return a;
|
||||
}
|
||||
|
||||
__host__ __device__ __forceinline__ cuda::std::tuple<float, float> operator()()
|
||||
{
|
||||
#ifdef __CUDA_ARCH__
|
||||
unsigned seed = hash(blockIdx.x * blockDim.x + threadIdx.x + count);
|
||||
// thrust::generate may call operator() more than once per thread.
|
||||
// Hence, increment count by grid size to ensure uniqueness of seed
|
||||
count += blockDim.x * gridDim.x;
|
||||
#else
|
||||
unsigned seed = hash(0);
|
||||
#endif
|
||||
thrust::default_random_engine rng(seed);
|
||||
thrust::random::uniform_real_distribution<float> distrib;
|
||||
return cuda::std::make_tuple(distrib(rng), distrib(rng));
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Allocate GPU structs, launch kernel and clean up
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
bool cdpQuadtree(int warp_size)
|
||||
{
|
||||
// Constants to control the algorithm.
|
||||
const int num_points = 1024;
|
||||
const int max_depth = 8;
|
||||
const int min_points_per_node = 16;
|
||||
|
||||
// Allocate memory for points.
|
||||
thrust::device_vector<float> x_d0(num_points);
|
||||
thrust::device_vector<float> x_d1(num_points);
|
||||
thrust::device_vector<float> y_d0(num_points);
|
||||
thrust::device_vector<float> y_d1(num_points);
|
||||
|
||||
// Generate random points.
|
||||
Random_generator rnd;
|
||||
thrust::generate(
|
||||
thrust::make_zip_iterator(x_d0.begin(), y_d0.begin()), thrust::make_zip_iterator(x_d0.end(), y_d0.end()), rnd);
|
||||
|
||||
// Host structures to analyze the device ones.
|
||||
Points points_init[2];
|
||||
points_init[0].set(thrust::raw_pointer_cast(&x_d0[0]), thrust::raw_pointer_cast(&y_d0[0]));
|
||||
points_init[1].set(thrust::raw_pointer_cast(&x_d1[0]), thrust::raw_pointer_cast(&y_d1[0]));
|
||||
|
||||
// Allocate memory to store points.
|
||||
Points *points;
|
||||
checkCudaErrors(cudaMalloc((void **)&points, 2 * sizeof(Points)));
|
||||
checkCudaErrors(cudaMemcpy(points, points_init, 2 * sizeof(Points), cudaMemcpyHostToDevice));
|
||||
|
||||
// We could use a close form...
|
||||
int max_nodes = 0;
|
||||
|
||||
for (int i = 0, num_nodes_at_level = 1; i < max_depth; ++i, num_nodes_at_level *= 4)
|
||||
max_nodes += num_nodes_at_level;
|
||||
|
||||
// Allocate memory to store the tree.
|
||||
Quadtree_node root;
|
||||
root.set_range(0, num_points);
|
||||
Quadtree_node *nodes;
|
||||
checkCudaErrors(cudaMalloc((void **)&nodes, max_nodes * sizeof(Quadtree_node)));
|
||||
checkCudaErrors(cudaMemcpy(nodes, &root, sizeof(Quadtree_node), cudaMemcpyHostToDevice));
|
||||
|
||||
// Build the quadtree.
|
||||
Parameters params(max_depth, min_points_per_node);
|
||||
std::cout << "Launching CDP kernel to build the quadtree" << std::endl;
|
||||
const int NUM_THREADS_PER_BLOCK = 128; // Do not use less than 128 threads.
|
||||
const int NUM_WARPS_PER_BLOCK = NUM_THREADS_PER_BLOCK / warp_size;
|
||||
const size_t smem_size = 4 * NUM_WARPS_PER_BLOCK * sizeof(int);
|
||||
build_quadtree_kernel<NUM_THREADS_PER_BLOCK><<<1, NUM_THREADS_PER_BLOCK, smem_size>>>(nodes, points, params);
|
||||
checkCudaErrors(cudaGetLastError());
|
||||
|
||||
// Copy points to CPU.
|
||||
thrust::host_vector<float> x_h(x_d0);
|
||||
thrust::host_vector<float> y_h(y_d0);
|
||||
Points host_points;
|
||||
host_points.set(thrust::raw_pointer_cast(&x_h[0]), thrust::raw_pointer_cast(&y_h[0]));
|
||||
|
||||
// Copy nodes to CPU.
|
||||
Quadtree_node *host_nodes = new Quadtree_node[max_nodes];
|
||||
checkCudaErrors(cudaMemcpy(host_nodes, nodes, max_nodes * sizeof(Quadtree_node), cudaMemcpyDeviceToHost));
|
||||
|
||||
// Validate the results.
|
||||
bool ok = check_quadtree(host_nodes, 0, num_points, &host_points, params);
|
||||
std::cout << "Results: " << (ok ? "OK" : "FAILED") << std::endl;
|
||||
|
||||
// Free CPU memory.
|
||||
delete[] host_nodes;
|
||||
|
||||
// Free memory.
|
||||
checkCudaErrors(cudaFree(nodes));
|
||||
checkCudaErrors(cudaFree(points));
|
||||
|
||||
return ok;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Main entry point.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
// Find/set the device.
|
||||
// The test requires an architecture SM35 or greater (CDP capable).
|
||||
int cuda_device = findCudaDevice(argc, (const char **)argv);
|
||||
cudaDeviceProp deviceProps;
|
||||
checkCudaErrors(cudaGetDeviceProperties(&deviceProps, cuda_device));
|
||||
int cdpCapable = (deviceProps.major == 3 && deviceProps.minor >= 5) || deviceProps.major >= 4;
|
||||
|
||||
printf(
|
||||
"GPU device %s has compute capabilities (SM %d.%d)\n", deviceProps.name, deviceProps.major, deviceProps.minor);
|
||||
|
||||
if (!cdpCapable) {
|
||||
std::cerr << "cdpQuadTree requires SM 3.5 or higher to use CUDA Dynamic "
|
||||
"Parallelism. Exiting...\n"
|
||||
<< std::endl;
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
bool ok = cdpQuadtree(deviceProps.warpSize);
|
||||
|
||||
return (ok ? EXIT_SUCCESS : EXIT_FAILURE);
|
||||
}
|
||||
18
cpp/3_CUDA_Features/cdpSimplePrint/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/cdpSimplePrint/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/cdpSimplePrint/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/cdpSimplePrint/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
43
cpp/3_CUDA_Features/cdpSimplePrint/CMakeLists.txt
Normal file
43
cpp/3_CUDA_Features/cdpSimplePrint/CMakeLists.txt
Normal file
@@ -0,0 +1,43 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(cdpSimplePrint LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# The aarch64/sbsa_aarch64 CUDA toolkit are support on Tegra since 13.0, so need to check which version of the toolkit is installed
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-linux" _aarch64_linux_ctk)
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-qnx" _aarch64_qnx_ctk)
|
||||
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" AND (NOT _aarch64_linux_ctk EQUAL -1 OR NOT _aarch64_qnx_ctk EQUAL -1))
|
||||
set(CMAKE_CUDA_ARCHITECTURES 87 110)
|
||||
else()
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 89 90 100 110 120)
|
||||
endif()
|
||||
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for cdpSimplePrint
|
||||
add_executable(cdpSimplePrint cdpSimplePrint.cu)
|
||||
|
||||
target_compile_options(cdpSimplePrint PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(cdpSimplePrint PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(cdpSimplePrint PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
34
cpp/3_CUDA_Features/cdpSimplePrint/README.md
Normal file
34
cpp/3_CUDA_Features/cdpSimplePrint/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# cdpSimplePrint - Simple Print (CUDA Dynamic Parallelism)
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates simple printf implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Dynamic Parallelism
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaDeviceSynchronize, cudaGetLastError, cudaGetDeviceProperties, cudaDeviceSetLimit
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[CDP](../../../README.md#cuda-dynamic-parallellism)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
161
cpp/3_CUDA_Features/cdpSimplePrint/cdpSimplePrint.cu
Normal file
161
cpp/3_CUDA_Features/cdpSimplePrint/cdpSimplePrint.cu
Normal file
@@ -0,0 +1,161 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_string.h>
|
||||
#include <iostream>
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Variable on the GPU used to generate unique identifiers of blocks.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
__device__ int g_uids = 0;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Print a simple message to signal the block which is currently executing.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
__device__ void print_info(int depth, int thread, int uid, int parent_uid)
|
||||
{
|
||||
if (threadIdx.x == 0) {
|
||||
if (depth == 0)
|
||||
printf("BLOCK %d launched by the host\n", uid);
|
||||
else {
|
||||
char buffer[32];
|
||||
|
||||
for (int i = 0; i < depth; ++i) {
|
||||
buffer[3 * i + 0] = '|';
|
||||
buffer[3 * i + 1] = ' ';
|
||||
buffer[3 * i + 2] = ' ';
|
||||
}
|
||||
|
||||
buffer[3 * depth] = '\0';
|
||||
printf("%sBLOCK %d launched by thread %d of block %d\n", buffer, uid, thread, parent_uid);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// The kernel using CUDA dynamic parallelism.
|
||||
//
|
||||
// It generates a unique identifier for each block. Prints the information
|
||||
// about that block. Finally, if the 'max_depth' has not been reached, the
|
||||
// block launches new blocks directly from the GPU.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
__global__ void cdp_kernel(int max_depth, int depth, int thread, int parent_uid)
|
||||
{
|
||||
// We create a unique ID per block. Thread 0 does that and shares the value
|
||||
// with the other threads.
|
||||
__shared__ int s_uid;
|
||||
|
||||
if (threadIdx.x == 0) {
|
||||
s_uid = atomicAdd(&g_uids, 1);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// We print the ID of the block and information about its parent.
|
||||
print_info(depth, thread, s_uid, parent_uid);
|
||||
|
||||
// We launch new blocks if we haven't reached the max_depth yet.
|
||||
if (++depth >= max_depth) {
|
||||
return;
|
||||
}
|
||||
|
||||
cdp_kernel<<<gridDim.x, blockDim.x>>>(max_depth, depth, threadIdx.x, s_uid);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Main entry point.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
printf("starting Simple Print (CUDA Dynamic Parallelism)\n");
|
||||
|
||||
// Parse a few command-line arguments.
|
||||
int max_depth = 2;
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "help") || checkCmdLineFlag(argc, (const char **)argv, "h")) {
|
||||
printf("Usage: %s depth=<max_depth>\t(where max_depth is a value between 1 "
|
||||
"and 8).\n",
|
||||
argv[0]);
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "depth")) {
|
||||
max_depth = getCmdLineArgumentInt(argc, (const char **)argv, "depth");
|
||||
|
||||
if (max_depth < 1 || max_depth > 8) {
|
||||
printf("depth parameter has to be between 1 and 8\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
// Find/set the device.
|
||||
int device = -1;
|
||||
cudaDeviceProp deviceProp;
|
||||
device = findCudaDevice(argc, (const char **)argv);
|
||||
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, device));
|
||||
|
||||
if (!(deviceProp.major > 3 || (deviceProp.major == 3 && deviceProp.minor >= 5))) {
|
||||
printf("GPU %d - %s does not support CUDA Dynamic Parallelism\n Exiting.", device, deviceProp.name);
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
// Print a message describing what the sample does.
|
||||
printf("*********************************************************************"
|
||||
"******\n");
|
||||
printf("The CPU launches 2 blocks of 2 threads each. On the device each thread "
|
||||
"will\n");
|
||||
printf("launch 2 blocks of 2 threads each. The GPU we will do that "
|
||||
"recursively\n");
|
||||
printf("until it reaches max_depth=%d\n\n", max_depth);
|
||||
printf("In total 2");
|
||||
int num_blocks = 2, sum = 2;
|
||||
|
||||
for (int i = 1; i < max_depth; ++i) {
|
||||
num_blocks *= 4;
|
||||
printf("+%d", num_blocks);
|
||||
sum += num_blocks;
|
||||
}
|
||||
|
||||
printf("=%d blocks are launched!!! (%d from the GPU)\n", sum, sum - 2);
|
||||
printf("************************************************************************"
|
||||
"***\n\n");
|
||||
|
||||
// Launch the kernel from the CPU.
|
||||
printf("Launching cdp_kernel() with CUDA Dynamic Parallelism:\n\n");
|
||||
cdp_kernel<<<2, 2>>>(max_depth, 0, 0, -1);
|
||||
checkCudaErrors(cudaGetLastError());
|
||||
|
||||
// Finalize.
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
18
cpp/3_CUDA_Features/cdpSimpleQuicksort/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/cdpSimpleQuicksort/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/cdpSimpleQuicksort/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/cdpSimpleQuicksort/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
43
cpp/3_CUDA_Features/cdpSimpleQuicksort/CMakeLists.txt
Normal file
43
cpp/3_CUDA_Features/cdpSimpleQuicksort/CMakeLists.txt
Normal file
@@ -0,0 +1,43 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(cdpSimpleQuicksort LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# The aarch64/sbsa_aarch64 CUDA toolkit are support on Tegra since 13.0, so need to check which version of the toolkit is installed
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-linux" _aarch64_linux_ctk)
|
||||
string(FIND "${CUDAToolkit_INCLUDE_DIRS}" "aarch64-qnx" _aarch64_qnx_ctk)
|
||||
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" AND (NOT _aarch64_linux_ctk EQUAL -1 OR NOT _aarch64_qnx_ctk EQUAL -1))
|
||||
set(CMAKE_CUDA_ARCHITECTURES 87 110)
|
||||
else()
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 89 90 100 110 120)
|
||||
endif()
|
||||
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for cdpSimpleQuicksort
|
||||
add_executable(cdpSimpleQuicksort cdpSimpleQuicksort.cu)
|
||||
|
||||
target_compile_options(cdpSimpleQuicksort PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(cdpSimpleQuicksort PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(cdpSimpleQuicksort PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
34
cpp/3_CUDA_Features/cdpSimpleQuicksort/README.md
Normal file
34
cpp/3_CUDA_Features/cdpSimpleQuicksort/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# cdpSimpleQuicksort - Simple Quicksort (CUDA Dynamic Parallelism)
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates simple quicksort implemented using CUDA Dynamic Parallelism. This sample requires devices with compute capability 3.5 or higher.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Dynamic Parallelism
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaStreamCreateWithFlags, cudaMemcpy, cudaStreamDestroy, cudaFree, cudaDeviceSynchronize, cudaDeviceSetLimit, cudaMalloc, cudaGetDeviceProperties
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[CDP](../../../README.md#cuda-dynamic-parallellism)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
245
cpp/3_CUDA_Features/cdpSimpleQuicksort/cdpSimpleQuicksort.cu
Normal file
245
cpp/3_CUDA_Features/cdpSimpleQuicksort/cdpSimpleQuicksort.cu
Normal file
@@ -0,0 +1,245 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_string.h>
|
||||
#include <iostream>
|
||||
|
||||
#define MAX_DEPTH 16
|
||||
#define INSERTION_SORT 32
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Selection sort used when depth gets too big or the number of elements drops
|
||||
// below a threshold.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
__device__ void selection_sort(unsigned int *data, int left, int right)
|
||||
{
|
||||
for (int i = left; i <= right; ++i) {
|
||||
unsigned min_val = data[i];
|
||||
int min_idx = i;
|
||||
|
||||
// Find the smallest value in the range [left, right].
|
||||
for (int j = i + 1; j <= right; ++j) {
|
||||
unsigned val_j = data[j];
|
||||
|
||||
if (val_j < min_val) {
|
||||
min_idx = j;
|
||||
min_val = val_j;
|
||||
}
|
||||
}
|
||||
|
||||
// Swap the values.
|
||||
if (i != min_idx) {
|
||||
data[min_idx] = data[i];
|
||||
data[i] = min_val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Very basic quicksort algorithm, recursively launching the next level.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
__global__ void cdp_simple_quicksort(unsigned int *data, int left, int right, int depth)
|
||||
{
|
||||
// If we're too deep or there are few elements left, we use an insertion
|
||||
// sort...
|
||||
if (depth >= MAX_DEPTH || right - left <= INSERTION_SORT) {
|
||||
selection_sort(data, left, right);
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned int *lptr = data + left;
|
||||
unsigned int *rptr = data + right;
|
||||
unsigned int pivot = data[(left + right) / 2];
|
||||
|
||||
// Do the partitioning.
|
||||
while (lptr <= rptr) {
|
||||
// Find the next left- and right-hand values to swap
|
||||
unsigned int lval = *lptr;
|
||||
unsigned int rval = *rptr;
|
||||
|
||||
// Move the left pointer as long as the pointed element is smaller than the
|
||||
// pivot.
|
||||
while (lval < pivot) {
|
||||
lptr++;
|
||||
lval = *lptr;
|
||||
}
|
||||
|
||||
// Move the right pointer as long as the pointed element is larger than the
|
||||
// pivot.
|
||||
while (rval > pivot) {
|
||||
rptr--;
|
||||
rval = *rptr;
|
||||
}
|
||||
|
||||
// If the swap points are valid, do the swap!
|
||||
if (lptr <= rptr) {
|
||||
*lptr++ = rval;
|
||||
*rptr-- = lval;
|
||||
}
|
||||
}
|
||||
|
||||
// Now the recursive part
|
||||
int nright = rptr - data;
|
||||
int nleft = lptr - data;
|
||||
|
||||
// Launch a new block to sort the left part.
|
||||
if (left < (rptr - data)) {
|
||||
cudaStream_t s;
|
||||
cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking);
|
||||
cdp_simple_quicksort<<<1, 1, 0, s>>>(data, left, nright, depth + 1);
|
||||
cudaStreamDestroy(s);
|
||||
}
|
||||
|
||||
// Launch a new block to sort the right part.
|
||||
if ((lptr - data) < right) {
|
||||
cudaStream_t s1;
|
||||
cudaStreamCreateWithFlags(&s1, cudaStreamNonBlocking);
|
||||
cdp_simple_quicksort<<<1, 1, 0, s1>>>(data, nleft, right, depth + 1);
|
||||
cudaStreamDestroy(s1);
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Call the quicksort kernel from the host.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
void run_qsort(unsigned int *data, unsigned int nitems)
|
||||
{
|
||||
// Prepare CDP for the max depth 'MAX_DEPTH'.
|
||||
|
||||
// Launch on device
|
||||
int left = 0;
|
||||
int right = nitems - 1;
|
||||
std::cout << "Launching kernel on the GPU" << std::endl;
|
||||
cdp_simple_quicksort<<<1, 1>>>(data, left, right, 0);
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Initialize data on the host.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
void initialize_data(unsigned int *dst, unsigned int nitems)
|
||||
{
|
||||
// Fixed seed for illustration
|
||||
srand(2047);
|
||||
|
||||
// Fill dst with random values
|
||||
for (unsigned i = 0; i < nitems; i++)
|
||||
dst[i] = rand() % nitems;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Verify the results.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
void check_results(int n, unsigned int *results_d)
|
||||
{
|
||||
unsigned int *results_h = new unsigned[n];
|
||||
checkCudaErrors(cudaMemcpy(results_h, results_d, n * sizeof(unsigned), cudaMemcpyDeviceToHost));
|
||||
|
||||
for (int i = 1; i < n; ++i)
|
||||
if (results_h[i - 1] > results_h[i]) {
|
||||
std::cout << "Invalid item[" << i - 1 << "]: " << results_h[i - 1] << " greater than " << results_h[i]
|
||||
<< std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
std::cout << "OK" << std::endl;
|
||||
delete[] results_h;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Main entry point.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int num_items = 128;
|
||||
bool verbose = false;
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "help") || checkCmdLineFlag(argc, (const char **)argv, "h")) {
|
||||
std::cerr << "Usage: " << argv[0]
|
||||
<< " num_items=<num_items>\twhere num_items is the number of "
|
||||
"items to sort"
|
||||
<< std::endl;
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "v")) {
|
||||
verbose = true;
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "num_items")) {
|
||||
num_items = getCmdLineArgumentInt(argc, (const char **)argv, "num_items");
|
||||
|
||||
if (num_items < 1) {
|
||||
std::cerr << "ERROR: num_items has to be greater than 1" << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
// Find/set device and get device properties
|
||||
int device = -1;
|
||||
cudaDeviceProp deviceProp;
|
||||
device = findCudaDevice(argc, (const char **)argv);
|
||||
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, device));
|
||||
|
||||
if (!(deviceProp.major > 3 || (deviceProp.major == 3 && deviceProp.minor >= 5))) {
|
||||
printf("GPU %d - %s does not support CUDA Dynamic Parallelism\n Exiting.", device, deviceProp.name);
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
// Create input data
|
||||
unsigned int *h_data = 0;
|
||||
unsigned int *d_data = 0;
|
||||
|
||||
// Allocate CPU memory and initialize data.
|
||||
std::cout << "Initializing data:" << std::endl;
|
||||
h_data = (unsigned int *)malloc(num_items * sizeof(unsigned int));
|
||||
initialize_data(h_data, num_items);
|
||||
|
||||
if (verbose) {
|
||||
for (int i = 0; i < num_items; i++)
|
||||
std::cout << "Data [" << i << "]: " << h_data[i] << std::endl;
|
||||
}
|
||||
|
||||
// Allocate GPU memory.
|
||||
checkCudaErrors(cudaMalloc((void **)&d_data, num_items * sizeof(unsigned int)));
|
||||
checkCudaErrors(cudaMemcpy(d_data, h_data, num_items * sizeof(unsigned int), cudaMemcpyHostToDevice));
|
||||
|
||||
// Execute
|
||||
std::cout << "Running quicksort on " << num_items << " elements" << std::endl;
|
||||
run_qsort(d_data, num_items);
|
||||
|
||||
// Check result
|
||||
std::cout << "Validating results: ";
|
||||
check_results(num_items, d_data);
|
||||
|
||||
free(h_data);
|
||||
checkCudaErrors(cudaFree(d_data));
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
18
cpp/3_CUDA_Features/cudaCompressibleMemory/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/cudaCompressibleMemory/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/cudaCompressibleMemory/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/cudaCompressibleMemory/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
42
cpp/3_CUDA_Features/cudaCompressibleMemory/CMakeLists.txt
Normal file
42
cpp/3_CUDA_Features/cudaCompressibleMemory/CMakeLists.txt
Normal file
@@ -0,0 +1,42 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(cudaCompressibleMemory LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for cudaCompressibleMemory
|
||||
add_executable(cudaCompressibleMemory compMalloc.cpp saxpy.cu)
|
||||
|
||||
target_compile_options(cudaCompressibleMemory PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(cudaCompressibleMemory PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(cudaCompressibleMemory PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
target_include_directories(cudaCompressibleMemory PRIVATE
|
||||
${CUDAToolkit_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
target_link_libraries(cudaCompressibleMemory PRIVATE
|
||||
CUDA::cuda_driver
|
||||
)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
35
cpp/3_CUDA_Features/cudaCompressibleMemory/README.md
Normal file
35
cpp/3_CUDA_Features/cudaCompressibleMemory/README.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# cudaCompressibleMemory - CUDA Compressible Memory
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates the compressible memory allocation using cuMemMap API.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Driver API, Compressible Memory, MMAP
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 5.0 ](https://developer.nvidia.com/cuda-gpus) [SM 5.2 ](https://developer.nvidia.com/cuda-gpus) [SM 5.3 ](https://developer.nvidia.com/cuda-gpus) [SM 6.0 ](https://developer.nvidia.com/cuda-gpus) [SM 6.1 ](https://developer.nvidia.com/cuda-gpus) [SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows, QNX
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, aarch64
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Driver API](http://docs.nvidia.com/cuda/cuda-driver-api/index.html)
|
||||
cuMemGetAllocationPropertiesFromHandle, cuMemCreate, cuDeviceGetAttribute, cuCtxGetDevice, cuMemGetAllocationGranularity, cuMemAddressFree, cuMemUnmap, cuMemMap, cuMemRelease, cuMemAddressReserve, cuMemSetAccess
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaEventSynchronize, cudaEventRecord, cudaEventElapsedTime, cudaOccupancyMaxPotentialBlockSize, cudaEventCreate
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
|
||||
## References (for more details)
|
||||
115
cpp/3_CUDA_Features/cudaCompressibleMemory/compMalloc.cpp
Normal file
115
cpp/3_CUDA_Features/cudaCompressibleMemory/compMalloc.cpp
Normal file
@@ -0,0 +1,115 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cuda.h>
|
||||
#include <cuda_runtime_api.h>
|
||||
#include <helper_cuda.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
cudaError_t setProp(CUmemAllocationProp *prop, bool UseCompressibleMemory)
|
||||
{
|
||||
CUdevice currentDevice;
|
||||
if (cuCtxGetDevice(¤tDevice) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
|
||||
memset(prop, 0, sizeof(CUmemAllocationProp));
|
||||
prop->type = CU_MEM_ALLOCATION_TYPE_PINNED;
|
||||
prop->location.type = CU_MEM_LOCATION_TYPE_DEVICE;
|
||||
prop->location.id = currentDevice;
|
||||
|
||||
if (UseCompressibleMemory)
|
||||
prop->allocFlags.compressionType = CU_MEM_ALLOCATION_COMP_GENERIC;
|
||||
|
||||
return cudaSuccess;
|
||||
}
|
||||
|
||||
cudaError_t allocateCompressible(void **adr, size_t size, bool UseCompressibleMemory)
|
||||
{
|
||||
CUmemAllocationProp prop = {};
|
||||
cudaError_t err = setProp(&prop, UseCompressibleMemory);
|
||||
if (err != cudaSuccess)
|
||||
return err;
|
||||
|
||||
size_t granularity = 0;
|
||||
if (cuMemGetAllocationGranularity(&granularity, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
size = ((size - 1) / granularity + 1) * granularity;
|
||||
CUdeviceptr dptr;
|
||||
if (cuMemAddressReserve(&dptr, size, 0, 0, 0) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
|
||||
CUmemGenericAllocationHandle allocationHandle;
|
||||
if (cuMemCreate(&allocationHandle, size, &prop, 0) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
|
||||
// Check if cuMemCreate was able to allocate compressible memory.
|
||||
if (UseCompressibleMemory) {
|
||||
CUmemAllocationProp allocationProp = {};
|
||||
cuMemGetAllocationPropertiesFromHandle(&allocationProp, allocationHandle);
|
||||
if (allocationProp.allocFlags.compressionType != CU_MEM_ALLOCATION_COMP_GENERIC) {
|
||||
printf("Could not allocate compressible memory... so waiving execution\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
}
|
||||
|
||||
if (cuMemMap(dptr, size, 0, allocationHandle, 0) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
|
||||
if (cuMemRelease(allocationHandle) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
|
||||
CUmemAccessDesc accessDescriptor;
|
||||
accessDescriptor.location.id = prop.location.id;
|
||||
accessDescriptor.location.type = prop.location.type;
|
||||
accessDescriptor.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
|
||||
|
||||
if (cuMemSetAccess(dptr, size, &accessDescriptor, 1) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
|
||||
*adr = (void *)dptr;
|
||||
return cudaSuccess;
|
||||
}
|
||||
|
||||
cudaError_t freeCompressible(void *ptr, size_t size, bool UseCompressibleMemory)
|
||||
{
|
||||
CUmemAllocationProp prop = {};
|
||||
cudaError_t err = setProp(&prop, UseCompressibleMemory);
|
||||
if (err != cudaSuccess)
|
||||
return err;
|
||||
|
||||
size_t granularity = 0;
|
||||
if (cuMemGetAllocationGranularity(&granularity, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM) != CUDA_SUCCESS)
|
||||
return cudaErrorMemoryAllocation;
|
||||
size = ((size - 1) / granularity + 1) * granularity;
|
||||
|
||||
if (ptr == NULL)
|
||||
return cudaSuccess;
|
||||
if (cuMemUnmap((CUdeviceptr)ptr, size) != CUDA_SUCCESS || cuMemAddressFree((CUdeviceptr)ptr, size) != CUDA_SUCCESS)
|
||||
return cudaErrorInvalidValue;
|
||||
return cudaSuccess;
|
||||
}
|
||||
34
cpp/3_CUDA_Features/cudaCompressibleMemory/compMalloc.h
Normal file
34
cpp/3_CUDA_Features/cudaCompressibleMemory/compMalloc.h
Normal file
@@ -0,0 +1,34 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef COMP_MALLOC_H
|
||||
#define COMP_MALLOC_H
|
||||
|
||||
cudaError_t allocateCompressible(void **adr, size_t size, bool UseCompressibleMemory);
|
||||
cudaError_t freeCompressible(void *ptr, size_t size, bool UseCompressibleMemory);
|
||||
|
||||
#endif
|
||||
192
cpp/3_CUDA_Features/cudaCompressibleMemory/saxpy.cu
Normal file
192
cpp/3_CUDA_Features/cudaCompressibleMemory/saxpy.cu
Normal file
@@ -0,0 +1,192 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
//
|
||||
// This sample uses the compressible memory allocation if device supports it
|
||||
// and performs saxpy on it.
|
||||
// Compressible memory may give better performance if the data is amenable to
|
||||
// compression.
|
||||
|
||||
#include <cuda.h>
|
||||
#include <stdio.h>
|
||||
#define CUDA_DRIVER_API
|
||||
#include "compMalloc.h"
|
||||
#include "helper_cuda.h"
|
||||
|
||||
__global__ void saxpy(const float a, const float4 *x, const float4 *y, float4 *z, const size_t n)
|
||||
{
|
||||
for (size_t i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) {
|
||||
const float4 x4 = x[i];
|
||||
const float4 y4 = y[i];
|
||||
z[i] = make_float4(a * x4.x + y4.x, a * x4.y + y4.y, a * x4.z + y4.z, a * x4.w + y4.w);
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void init(float4 *x, float4 *y, const float val, const size_t n)
|
||||
{
|
||||
const float4 val4 = make_float4(val, val, val, val);
|
||||
for (size_t i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) {
|
||||
x[i] = y[i] = val4;
|
||||
}
|
||||
}
|
||||
|
||||
void launchSaxpy(const float a,
|
||||
float4 *x,
|
||||
float4 *y,
|
||||
float4 *z,
|
||||
const size_t n,
|
||||
const float init_val,
|
||||
const bool compressibleZbuf)
|
||||
{
|
||||
cudaEvent_t start, stop;
|
||||
float ms;
|
||||
int blockSize;
|
||||
int minGridSize;
|
||||
dim3 threads, blocks;
|
||||
|
||||
if (!compressibleZbuf) {
|
||||
// We are on config where compressible buffer can only be initialized through cudaMemcpy
|
||||
// hence, x & y buffers are allocated as compressible and initialized via cudaMemcpy
|
||||
// whereas z buffer is allocated as non-compressible.
|
||||
float4 *h_x = (float4 *)malloc(sizeof(float4) * n);
|
||||
float4 *h_y = (float4 *)malloc(sizeof(float4) * n);
|
||||
for (int i = 0; i < n; i++) {
|
||||
h_x[i].x = h_x[i].y = h_x[i].z = h_x[i].w = init_val;
|
||||
h_y[i].x = h_y[i].y = h_y[i].z = h_y[i].w = init_val;
|
||||
}
|
||||
checkCudaErrors(cudaMemcpy(x, h_x, sizeof(float4) * n, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(y, h_y, sizeof(float4) * n, cudaMemcpyHostToDevice));
|
||||
free(h_x);
|
||||
free(h_y);
|
||||
}
|
||||
else {
|
||||
checkCudaErrors(cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, (void *)init));
|
||||
threads = dim3(blockSize, 1, 1);
|
||||
blocks = dim3(minGridSize, 1, 1);
|
||||
init<<<blocks, threads>>>(x, y, init_val, n);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, (void *)saxpy));
|
||||
threads = dim3(blockSize, 1, 1);
|
||||
blocks = dim3(minGridSize, 1, 1);
|
||||
|
||||
checkCudaErrors(cudaEventCreate(&start));
|
||||
checkCudaErrors(cudaEventCreate(&stop));
|
||||
checkCudaErrors(cudaEventRecord(start));
|
||||
saxpy<<<blocks, threads>>>(a, x, y, z, n);
|
||||
checkCudaErrors(cudaEventRecord(stop));
|
||||
checkCudaErrors(cudaEventSynchronize(stop));
|
||||
checkCudaErrors(cudaEventElapsedTime(&ms, start, stop));
|
||||
|
||||
const size_t size = n * sizeof(float4);
|
||||
printf("Running saxpy with %d blocks x %d threads = %.3f ms %.3f TB/s\n",
|
||||
blocks.x,
|
||||
threads.x,
|
||||
ms,
|
||||
(size * 3) / ms / 1e9);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const size_t n = 10485760;
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "help") || checkCmdLineFlag(argc, (const char **)argv, "?")) {
|
||||
printf("Usage -device=n (n >= 0 for deviceID)\n");
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
|
||||
findCudaDevice(argc, (const char **)argv);
|
||||
CUdevice currentDevice;
|
||||
checkCudaErrors(cuCtxGetDevice(¤tDevice));
|
||||
|
||||
// Check that the selected device supports virtual memory management
|
||||
int vmm_supported = -1;
|
||||
checkCudaErrors(
|
||||
cuDeviceGetAttribute(&vmm_supported, CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED, currentDevice));
|
||||
if (vmm_supported == 0) {
|
||||
printf("Device %d doesn't support Virtual Memory Management, waiving the execution.\n", currentDevice);
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
int isCompressionAvailable;
|
||||
checkCudaErrors(cuDeviceGetAttribute(
|
||||
&isCompressionAvailable, CU_DEVICE_ATTRIBUTE_GENERIC_COMPRESSION_SUPPORTED, currentDevice));
|
||||
if (isCompressionAvailable == 0) {
|
||||
printf("Device %d doesn't support Generic memory compression, waiving the execution.\n", currentDevice);
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
printf("Generic memory compression support is available\n");
|
||||
|
||||
int major, minor;
|
||||
checkCudaErrors(cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, currentDevice));
|
||||
checkCudaErrors(cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, currentDevice));
|
||||
float4 *x, *y, *z;
|
||||
const size_t size = n * sizeof(float4);
|
||||
|
||||
// Allocating compressible memory
|
||||
checkCudaErrors(allocateCompressible((void **)&x, size, true));
|
||||
checkCudaErrors(allocateCompressible((void **)&y, size, true));
|
||||
bool compressibleZbuf = 0;
|
||||
if ((major == 8 && minor == 0) || (major == 8 && minor == 6)) {
|
||||
// On SM 8.0 and 8.6 GPUs compressible buffer can only be initialized
|
||||
// through cudaMemcpy.
|
||||
printf("allocating non-compressible Z buffer\n");
|
||||
checkCudaErrors(allocateCompressible((void **)&z, size, false));
|
||||
compressibleZbuf = 0;
|
||||
}
|
||||
else {
|
||||
checkCudaErrors(allocateCompressible((void **)&z, size, true));
|
||||
compressibleZbuf = 1;
|
||||
}
|
||||
|
||||
printf("Running saxpy on %zu bytes of Compressible memory\n", size);
|
||||
|
||||
const float a = 1.0f;
|
||||
const float init_val = 1.0f;
|
||||
launchSaxpy(a, x, y, z, n, init_val, compressibleZbuf);
|
||||
|
||||
checkCudaErrors(freeCompressible(x, size, true));
|
||||
checkCudaErrors(freeCompressible(y, size, true));
|
||||
checkCudaErrors(freeCompressible(z, size, true));
|
||||
|
||||
printf("Running saxpy on %zu bytes of Non-Compressible memory\n", size);
|
||||
// Allocating non-compressible memory
|
||||
checkCudaErrors(allocateCompressible((void **)&x, size, false));
|
||||
checkCudaErrors(allocateCompressible((void **)&y, size, false));
|
||||
checkCudaErrors(allocateCompressible((void **)&z, size, false));
|
||||
|
||||
launchSaxpy(a, x, y, z, n, init_val, compressibleZbuf);
|
||||
|
||||
checkCudaErrors(freeCompressible(x, size, false));
|
||||
checkCudaErrors(freeCompressible(y, size, false));
|
||||
checkCudaErrors(freeCompressible(z, size, false));
|
||||
|
||||
printf("\nNOTE: The CUDA Samples are not meant for performance measurements. "
|
||||
"Results may vary when GPU Boost is enabled.\n");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
18
cpp/3_CUDA_Features/cudaTensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/cudaTensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/cudaTensorCoreGemm/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/cudaTensorCoreGemm/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
35
cpp/3_CUDA_Features/cudaTensorCoreGemm/CMakeLists.txt
Normal file
35
cpp/3_CUDA_Features/cudaTensorCoreGemm/CMakeLists.txt
Normal file
@@ -0,0 +1,35 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(cudaTensorCoreGemm LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for cudaTensorCoreGemm
|
||||
add_executable(cudaTensorCoreGemm cudaTensorCoreGemm.cu)
|
||||
|
||||
target_compile_options(cudaTensorCoreGemm PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(cudaTensorCoreGemm PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(cudaTensorCoreGemm PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
36
cpp/3_CUDA_Features/cudaTensorCoreGemm/README.md
Normal file
36
cpp/3_CUDA_Features/cudaTensorCoreGemm/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# cudaTensorCoreGemm - CUDA Tensor Core GEMM
|
||||
|
||||
## Description
|
||||
|
||||
CUDA sample demonstrating a GEMM computation using the Warp Matrix Multiply and Accumulate (WMMA) API introduced in CUDA 9.
|
||||
|
||||
This sample demonstrates the use of the new CUDA WMMA API employing the Tensor Cores introduced in the Volta chip family for faster matrix operations.
|
||||
|
||||
In addition to that, it demonstrates the use of the new CUDA function attribute cudaFuncAttributeMaxDynamicSharedMemorySize that allows the application to reserve an extended amount of shared memory than it is available by default.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Matrix Multiply, WMMA, Tensor Cores
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, aarch64
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaFree, cudaGetErrorString, cudaGetLastError, cudaEventSynchronize, cudaFuncSetAttribute, cudaEventRecord, cudaMemset, cudaMalloc, cudaEventElapsedTime, cudaGetDeviceProperties, cudaEventCreate
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
|
||||
## References (for more details)
|
||||
617
cpp/3_CUDA_Features/cudaTensorCoreGemm/cudaTensorCoreGemm.cu
Normal file
617
cpp/3_CUDA_Features/cudaTensorCoreGemm/cudaTensorCoreGemm.cu
Normal file
@@ -0,0 +1,617 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// CUDA sample demonstrating a GEMM computation using the Warp Matrix Multiply
|
||||
// and Accumulate API introduced in CUDA 9.
|
||||
|
||||
// In this program, the compute_gemm kernel computes the result of a matrix
|
||||
// multiplication and addition: D = alpha * A * B + beta * C. The dimensions of
|
||||
// both C and D matrices are M_GLOBAL x N_GLOBAL. The A matrix is M_GLOBAL x
|
||||
// K_GLOBAL (row-major), the B matrix is K_GLOBAL x N_GLOBAL (column-major). In
|
||||
// that kernel, each CTA computes one 128 x 128 tile of the resulting matrix per
|
||||
// iteration. When the tile is computed, the CTA stores it to the global memory
|
||||
// and begins a new iteration, selecting a new 128 x 128 tile to compute.
|
||||
// Each CTA consists of eight warps. For the 128 x 128 tile, each warp computes
|
||||
// eight 16 x 16 subtiles, organized in a 2 x 4 two-dimensional array. Warps
|
||||
// compute the 16 x 16 subtiles using nvcuda::wmma::mma_sync operations by
|
||||
// moving through the K_GLOBAL dimension of the A and B matrices and
|
||||
// accumulating the intermediate result in the local thread state.
|
||||
|
||||
// There are a number of simple optimizations used in the algorithm:
|
||||
// - The CTA copies the 128 x 128 tile of the C matrix from the global memory to
|
||||
// shared memory. After that is done, each warp loads the C matrix fragments
|
||||
// from shared memory, thus avoiding a random global memory access.
|
||||
// - On each internal iteration, the CTA copies a portion of the A and B
|
||||
// matrices from global memory to shared memory. After that, all warps in the
|
||||
// CTA reuse the A and B data from shared memory, thus reducing the number of
|
||||
// data copies from global memory.
|
||||
// - The portions of the A and B matrices are stored in shared memory with an
|
||||
// additional padding (skew) to reduce the number of shared memory access bank
|
||||
// conflicts.
|
||||
// (See a detailed explanation near the SKEW_HALF macro definition.)
|
||||
// - When the CTA finishes computing the tiles of the resulting matrix, each
|
||||
// warp stores its subtiles to shared memory. The CTA then copies the shared
|
||||
// memory contents to global memory, again avoiding redundant random global
|
||||
// memory accesses.
|
||||
// - Note that the CTA tile size is chosen to maximize the GPU register
|
||||
// utilization, but carefully enough to avoid local memory use.
|
||||
|
||||
#include <assert.h>
|
||||
#include <cuda.h>
|
||||
#include <mma.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// helper functions and utilities to work with CUDA
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_functions.h>
|
||||
|
||||
// Externally configurable parameters.
|
||||
|
||||
#ifndef CPU_DEBUG
|
||||
// Set this to 1 to verify the correctness of the GPU-computed matrix.
|
||||
#define CPU_DEBUG 0
|
||||
#endif
|
||||
|
||||
#ifndef SHARED_MEMORY_LIMIT_64K
|
||||
// Set this to 0 to use more than 64 Kb of shared memory to cache data, to
|
||||
// improve the performance of the computations on GPU.
|
||||
// Note that you need a GPU that can have more than 64 Kb of shared memory
|
||||
// per multiprocessor.
|
||||
#define SHARED_MEMORY_LIMIT_64K 1
|
||||
#endif
|
||||
|
||||
// GPU configuration.
|
||||
|
||||
#define WARP_SIZE 32
|
||||
|
||||
// MMA matrix tile dimensions.
|
||||
|
||||
#define M 16
|
||||
#define N 16
|
||||
#define K 16
|
||||
|
||||
#define WMMA_M 16
|
||||
#define WMMA_N 16
|
||||
#define WMMA_K 16
|
||||
|
||||
// GEMM configuration.
|
||||
|
||||
#define M_TILES 256
|
||||
#define N_TILES 256
|
||||
#define K_TILES 256
|
||||
|
||||
#define M_GLOBAL (M * M_TILES)
|
||||
#define N_GLOBAL (N * N_TILES)
|
||||
#define K_GLOBAL (K * K_TILES)
|
||||
|
||||
#define C_LAYOUT wmma::mem_row_major
|
||||
|
||||
// Implementation constants.
|
||||
|
||||
#define WARPS_PER_BLOCK 8
|
||||
#define THREADS_PER_BLOCK (WARP_SIZE * WARPS_PER_BLOCK)
|
||||
|
||||
#if SHARED_MEMORY_LIMIT_64K
|
||||
// With only 64 Kb shared memory available, we can fit two 8-tile chunks of
|
||||
// the A and B matrix data, that are 16 * 16 * 8 * 8 * 2 = 32 Kb each
|
||||
// (i.e. two 8x8 arrays of tiles of 16x16 half-typed elements per CTA).
|
||||
// But we cannot account the 8 Kb total skew overhead, without which the
|
||||
// performance would be severely impacted. So we choose to reduce the chunk size
|
||||
// in half, i.e. the amount of A and B matrix data we cache in shared memory.
|
||||
// Accordingly, this doubles the number of outer iterations across the global K
|
||||
// dimension, which only slightly impacts the performance.
|
||||
#define CHUNK_K 4
|
||||
#else
|
||||
#define CHUNK_K 8
|
||||
#endif
|
||||
|
||||
#define CHUNK_LINE_BYTES (CHUNK_K * K * sizeof(half))
|
||||
#define WARP_COPY_BYTES (WARP_SIZE * sizeof(int4))
|
||||
#define CHUNK_COPY_LINES_PER_WARP (WARP_COPY_BYTES / CHUNK_LINE_BYTES)
|
||||
#define CHUNK_COPY_LINE_LANES (WARP_SIZE / CHUNK_COPY_LINES_PER_WARP)
|
||||
|
||||
#define BLOCK_ROW_WARPS 2
|
||||
#define BLOCK_COL_WARPS 4
|
||||
|
||||
#define WARP_ROW_TILES 4
|
||||
#define WARP_COL_TILES 2
|
||||
|
||||
#define BLOCK_ROW_TILES (WARP_ROW_TILES * BLOCK_ROW_WARPS)
|
||||
#define BLOCK_COL_TILES (WARP_COL_TILES * BLOCK_COL_WARPS)
|
||||
|
||||
#define GLOBAL_MEM_STRIDE N_GLOBAL
|
||||
|
||||
#define SHMEM_STRIDE (N * BLOCK_ROW_TILES)
|
||||
#define SHMEM_OFFSET (N * WARP_ROW_TILES)
|
||||
|
||||
// The macro below is used to shift rows of the A matrix and columns of the B matrix
|
||||
// in shared memory to minimize possible bank conflicts.
|
||||
// Before performing the nvcuda::wmma::mma_sync operation, the warp must load the matrix
|
||||
// data using the nvcuda::wmma::load_matrix_sync operation. Although the memory access pattern
|
||||
// is not specified for that function, each lane in the warp can read one or multiple matrix
|
||||
// elements from different matrix rows or columns.
|
||||
// For shared memory, such access can result in bank conflicts if different rows / columns
|
||||
// of the matrix map to the same bank. By shifting each row and column by a few bytes, we
|
||||
// make sure that they map to different banks, thus reducing the number of possible bank
|
||||
// conflicts.
|
||||
// The number of 16 two-byte "half" elements is chosen as the minimum possible shift because
|
||||
// we must keep each row and column 256-bit aligned, as required by nvcuda::wmma::load_matrix_sync.
|
||||
#define SKEW_HALF 16
|
||||
|
||||
#define checkKernelErrors(expr) \
|
||||
do { \
|
||||
expr; \
|
||||
\
|
||||
cudaError_t __err = cudaGetLastError(); \
|
||||
if (__err != cudaSuccess) { \
|
||||
printf("Line %d: '%s' failed: %s\n", __LINE__, #expr, cudaGetErrorString(__err)); \
|
||||
abort(); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
using namespace nvcuda;
|
||||
|
||||
__host__ void init_host_matrices(half *a, half *b, float *c)
|
||||
{
|
||||
for (int i = 0; i < M_GLOBAL; i++) {
|
||||
for (int j = 0; j < K_GLOBAL; j++) {
|
||||
a[i * K_GLOBAL + j] = (half)(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < N_GLOBAL; i++) {
|
||||
for (int j = 0; j < K_GLOBAL; j++) {
|
||||
b[i * K_GLOBAL + j] = (half)(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
for (int t = 0; t < M_GLOBAL * N_GLOBAL; t++) {
|
||||
c[t] = static_cast<float>(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void compute_gemm(const half *A, const half *B, const float *C, float *D, float alpha, float beta)
|
||||
{
|
||||
extern __shared__ half shmem[][CHUNK_K * K + SKEW_HALF];
|
||||
|
||||
// Warp and lane identification.
|
||||
const unsigned int warpId = threadIdx.x / WARP_SIZE;
|
||||
const unsigned int laneId = threadIdx.x % WARP_SIZE;
|
||||
|
||||
// Offset in shared memory from which the B matrix is stored.
|
||||
const size_t shmem_idx_b_off = BLOCK_COL_TILES * M;
|
||||
|
||||
// This pointer is used to access the C and D matrix tiles this warp computes.
|
||||
float *shmem_warp_tile_ptr =
|
||||
(float *)&shmem[0][0] + (warpId / 2) * SHMEM_STRIDE * K * 2 + (warpId % 2) * SHMEM_OFFSET;
|
||||
|
||||
// This pointer is used to stream the C and D matrices block-wide tile to and
|
||||
// from shared memory.
|
||||
float *shmem_warp_stream_ptr = (float *)&shmem[0][0] + warpId * SHMEM_STRIDE * K;
|
||||
|
||||
// Adjust the beta scaler, as it'll be multiplied by alpha at the end of
|
||||
// each tile computation. Technically this is not generally correct (may
|
||||
// result in a loss of precision). Zero still needs to be specially handled
|
||||
// though.
|
||||
beta /= alpha;
|
||||
|
||||
// Each CTA slides along the 128 x 128 tiles from the top left corner of the
|
||||
// matrix to the right and down, and selects the next tile to compute. Once
|
||||
// there's no such tile, all warps in this CTA exit.
|
||||
for (unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) {
|
||||
const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES);
|
||||
const unsigned int block_tile_j = (block_pos * BLOCK_ROW_TILES) % N_TILES;
|
||||
|
||||
// Stop when there are no more D matrix tiles to compute in this CTA.
|
||||
if (block_tile_i >= M_TILES) {
|
||||
break;
|
||||
}
|
||||
|
||||
// This warp's pointer to the C matrix data to copy memory from to shared
|
||||
// memory.
|
||||
const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N;
|
||||
const float *src_gmem_warp_stream_ptr = &C[gmem_idx];
|
||||
|
||||
// Stream multiple C tiles to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < K; i++) {
|
||||
typedef int4 copy_t;
|
||||
|
||||
*((copy_t *)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId) =
|
||||
*((copy_t *)(src_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// These fragments will accumulate the result of A and B matrix fragment
|
||||
// multiplications along the K_GLOBAL dimension.
|
||||
wmma::fragment<wmma::accumulator, M, N, K, float> c[WARP_COL_TILES][WARP_ROW_TILES];
|
||||
|
||||
// Load the C matrix tiles into fragments from shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
const float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N;
|
||||
|
||||
wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Scale the C matrix.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < c[i][j].num_elements; t++) {
|
||||
c[i][j].x[t] *= beta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Select what warp copies what matrix to shared memory.
|
||||
// Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix.
|
||||
const half *warp_ptr = (warpId < 4) ? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % 4) * 2)
|
||||
: (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % 4) * 2);
|
||||
|
||||
// Go through the global K dimension by a fixed step at a time.
|
||||
#pragma unroll
|
||||
for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) {
|
||||
// Copy slices of the A and B matrices to shared memory.
|
||||
// The first half of the warps in the CTA copy the A matrix, the rest copy
|
||||
// the B matrix.
|
||||
size_t shmem_idx = warpId < (WARPS_PER_BLOCK / 2)
|
||||
? (M * (warpId % (WARPS_PER_BLOCK / 2)) * 2)
|
||||
: (N * (warpId % (WARPS_PER_BLOCK / 2)) * 2 + shmem_idx_b_off);
|
||||
|
||||
// First half of the warp copies the first row / column of the matrix,
|
||||
// the second half of the warp copies the next.
|
||||
int4 *lane_ptr = (int4 *)(warp_ptr + tile_k * K + (laneId / CHUNK_COPY_LINE_LANES) * K_GLOBAL)
|
||||
+ (laneId % CHUNK_COPY_LINE_LANES);
|
||||
|
||||
// Shift the second half of the warp to the next row / column in the
|
||||
// shared memory.
|
||||
shmem_idx += laneId / CHUNK_COPY_LINE_LANES;
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ((WARP_SIZE / 2) / CHUNK_COPY_LINES_PER_WARP) * 2; i++) {
|
||||
// Copy 16 bytes at once in each lane.
|
||||
*((int4 *)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES)) = *lane_ptr;
|
||||
|
||||
// Advance the global memory pointer and the shared memory index.
|
||||
lane_ptr = (int4 *)((half *)lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP);
|
||||
shmem_idx += CHUNK_COPY_LINES_PER_WARP;
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Compute a grid of C matrix tiles in each warp.
|
||||
#pragma unroll
|
||||
for (int k_step = 0; k_step < CHUNK_K; k_step++) {
|
||||
wmma::fragment<wmma::matrix_a, M, N, K, half, wmma::row_major> a[WARP_COL_TILES];
|
||||
wmma::fragment<wmma::matrix_b, M, N, K, half, wmma::col_major> b[WARP_ROW_TILES];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
size_t shmem_idx_a = (warpId / 2) * M * 2 + (i * M);
|
||||
const half *tile_ptr = &shmem[shmem_idx_a][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_HALF);
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
if (i == 0) {
|
||||
// Load the B matrix fragment once, because it is going to be
|
||||
// reused against the other A matrix fragments.
|
||||
size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId % 2) + (j * N);
|
||||
const half *tile_ptr = &shmem[shmem_idx_b][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_HALF);
|
||||
}
|
||||
|
||||
wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
// Store the D fragments to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
#pragma unroll
|
||||
// Uniform, point-wise transformations of ALL fragment elements by ALL
|
||||
// threads in the warp are well-defined even though element indices
|
||||
// within fragment storage are not defined.
|
||||
for (int t = 0; t < c[i][j].num_elements; t++)
|
||||
c[i][j].x[t] *= alpha;
|
||||
|
||||
float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N;
|
||||
|
||||
wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Now that shared memory contains all the D tiles, stream them to global
|
||||
// memory.
|
||||
float *dst_gmem_warp_stream_ptr = &D[gmem_idx];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < K; i++) {
|
||||
*((int4 *)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) =
|
||||
*((int4 *)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
|
||||
// Performs an MxNxK GEMM (C=alpha*A*B + beta*C) assuming:
|
||||
// 1) Matrices are packed in memory.
|
||||
// 2) M, N and K are multiples of 16.
|
||||
// 3) Neither A nor B are transposed.
|
||||
// Note: This is a less performant version of the compute_gemm kernel. It is
|
||||
// designed for
|
||||
// demonstration purposes only to show the CUDA WMMA API use without
|
||||
// relying on availability of the shared memory.
|
||||
__global__ void
|
||||
simple_wmma_gemm(half *a, half *b, float *c, float *d, int m_ld, int n_ld, int k_ld, float alpha, float beta)
|
||||
{
|
||||
// Leading dimensions. Packed with no transpositions.
|
||||
int lda = k_ld;
|
||||
int ldb = k_ld;
|
||||
int ldc = n_ld;
|
||||
|
||||
// Tile using a 2D grid
|
||||
int warpM = (blockIdx.x * blockDim.x + threadIdx.x) / warpSize;
|
||||
int warpN = (blockIdx.y * blockDim.y + threadIdx.y);
|
||||
|
||||
// Declare the fragments
|
||||
wmma::fragment<wmma::matrix_a, WMMA_M, WMMA_N, WMMA_K, half, wmma::row_major> a_frag;
|
||||
wmma::fragment<wmma::matrix_b, WMMA_M, WMMA_N, WMMA_K, half, wmma::col_major> b_frag;
|
||||
wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float> acc_frag;
|
||||
wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float> c_frag;
|
||||
|
||||
wmma::fill_fragment(acc_frag, 0.0f);
|
||||
|
||||
// Loop over k
|
||||
for (int i = 0; i < k_ld; i += WMMA_K) {
|
||||
int aCol = i;
|
||||
int aRow = warpM * WMMA_M;
|
||||
int bCol = warpN * N;
|
||||
int bRow = i;
|
||||
|
||||
// Bounds checking
|
||||
if (aRow < m_ld && aCol < k_ld && bRow < k_ld && bCol < n_ld) {
|
||||
// Load the inputs
|
||||
wmma::load_matrix_sync(a_frag, a + aCol + aRow * lda, lda);
|
||||
wmma::load_matrix_sync(b_frag, b + bRow + bCol * ldb, ldb);
|
||||
|
||||
// Perform the matrix multiplication
|
||||
wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag);
|
||||
}
|
||||
}
|
||||
|
||||
// Load in the current value of c, scale it by beta, and add this our result
|
||||
// scaled by alpha
|
||||
int cCol = warpN * WMMA_N;
|
||||
int cRow = warpM * WMMA_M;
|
||||
|
||||
if (cRow < m_ld && cCol < n_ld) {
|
||||
wmma::load_matrix_sync(c_frag, c + cCol + cRow * ldc, ldc, wmma::mem_row_major);
|
||||
|
||||
for (int i = 0; i < c_frag.num_elements; i++) {
|
||||
c_frag.x[i] = alpha * acc_frag.x[i] + beta * c_frag.x[i];
|
||||
}
|
||||
|
||||
// Store the output
|
||||
wmma::store_matrix_sync(d + cCol + cRow * ldc, c_frag, ldc, wmma::mem_row_major);
|
||||
}
|
||||
}
|
||||
|
||||
__host__ void matMultiplyOnHost(half *A,
|
||||
half *B,
|
||||
float *C,
|
||||
float alpha,
|
||||
float beta,
|
||||
int numARows,
|
||||
int numAColumns,
|
||||
int numBRows,
|
||||
int numBColumns,
|
||||
int numCRows,
|
||||
int numCColumns)
|
||||
{
|
||||
for (int i = 0; i < numCRows; i++) {
|
||||
for (int j = 0; j < numCColumns; j++) {
|
||||
float temp = 0.0;
|
||||
|
||||
for (int k = 0; k < numAColumns; k++) {
|
||||
temp += (float)A[i * numAColumns + k] * (float)B[j * numBRows + k];
|
||||
}
|
||||
|
||||
C[i * numCColumns + j] = temp * alpha + beta * C[i * numCColumns + j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
printf("Initializing...\n");
|
||||
|
||||
int dev = findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
cudaDeviceProp deviceProp;
|
||||
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, dev));
|
||||
|
||||
// Tensor cores require a GPU of Volta (SM7X) architecture or higher.
|
||||
if (deviceProp.major < 7) {
|
||||
printf("cudaTensorCoreGemm requires SM 7.0 or higher to use Tensor "
|
||||
"Cores. Exiting...\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
printf("M: %d (%d x %d)\n", M_GLOBAL, M, M_TILES);
|
||||
printf("N: %d (%d x %d)\n", N_GLOBAL, N, N_TILES);
|
||||
printf("K: %d (%d x %d)\n", K_GLOBAL, K, K_TILES);
|
||||
|
||||
half *A_h = NULL;
|
||||
half *B_h = NULL;
|
||||
float *C_h = NULL;
|
||||
#if CPU_DEBUG
|
||||
float *result_hD = NULL;
|
||||
float *result_host = NULL;
|
||||
#endif
|
||||
|
||||
A_h = (half *)malloc(sizeof(half) * M_GLOBAL * K_GLOBAL);
|
||||
B_h = (half *)malloc(sizeof(half) * K_GLOBAL * N_GLOBAL);
|
||||
C_h = (float *)malloc(sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
#if CPU_DEBUG
|
||||
result_hD = (float *)malloc(sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
result_host = (float *)malloc(sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
#endif
|
||||
|
||||
half *A = NULL;
|
||||
half *B = NULL;
|
||||
float *C = NULL;
|
||||
float *D = NULL;
|
||||
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&A), sizeof(half) * M_GLOBAL * K_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&B), sizeof(half) * N_GLOBAL * K_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&C), sizeof(float) * M_GLOBAL * N_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&D), sizeof(float) * M_GLOBAL * N_GLOBAL));
|
||||
|
||||
assert(((unsigned long long)A) % 128 == 0);
|
||||
assert(((unsigned long long)B) % 128 == 0);
|
||||
assert(((unsigned long long)C) % 128 == 0);
|
||||
assert(((unsigned long long)D) % 128 == 0);
|
||||
|
||||
init_host_matrices(A_h, B_h, C_h);
|
||||
|
||||
printf("Preparing data for GPU...\n");
|
||||
|
||||
checkCudaErrors(cudaMemcpy(A, A_h, sizeof(half) * M_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(B, B_h, sizeof(half) * N_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(C, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemset(D, 0, sizeof(float) * M_GLOBAL * N_GLOBAL));
|
||||
|
||||
enum {
|
||||
// Compute the right amount of shared memory to request.
|
||||
// We need shared memory to hold per-CTA C and D matrix tiles, and to cache
|
||||
// per-CTA chunks
|
||||
// of the A and B matrices. Therefore, the right amount to request is the
|
||||
// maximum of those
|
||||
// two numbers.
|
||||
SHMEM_SZ = MAX(sizeof(half) * (BLOCK_COL_TILES * M) * (CHUNK_K * K + SKEW_HALF) * 2,
|
||||
M * (BLOCK_ROW_WARPS * WARP_ROW_TILES) * N * (BLOCK_COL_WARPS * WARP_COL_TILES) * sizeof(float))
|
||||
};
|
||||
|
||||
printf("Required shared memory size: %lu Kb\n", SHMEM_SZ / 1024UL);
|
||||
|
||||
const float alpha = 1.1f;
|
||||
const float beta = 1.2f;
|
||||
|
||||
cudaEvent_t start, stop;
|
||||
|
||||
checkCudaErrors(cudaEventCreate(&start));
|
||||
checkCudaErrors(cudaEventCreate(&stop));
|
||||
checkCudaErrors(cudaEventRecord(start));
|
||||
|
||||
// If enough shared memory available on the GPU use high performant kernel
|
||||
if (deviceProp.sharedMemPerMultiprocessor >= SHMEM_SZ) {
|
||||
printf("Computing... using high performance kernel compute_gemm \n");
|
||||
|
||||
checkCudaErrors(cudaFuncSetAttribute(compute_gemm, cudaFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ));
|
||||
checkKernelErrors(
|
||||
(compute_gemm<<<deviceProp.multiProcessorCount, THREADS_PER_BLOCK, SHMEM_SZ>>>(A, B, C, D, alpha, beta)));
|
||||
#if CPU_DEBUG
|
||||
checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyDeviceToHost));
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
dim3 gridDim;
|
||||
dim3 blockDim;
|
||||
|
||||
// blockDim.x must be a multple of warpSize
|
||||
// 128x4 means we have 16 warps and a block computes a 64x64 output tile
|
||||
blockDim.x = 128;
|
||||
blockDim.y = 4;
|
||||
|
||||
gridDim.x = (M_GLOBAL + (WMMA_M * blockDim.x / 32 - 1)) / (WMMA_M * blockDim.x / 32);
|
||||
gridDim.y = (N_GLOBAL + WMMA_N * blockDim.y - 1) / (WMMA_N * blockDim.y);
|
||||
|
||||
printf("Computing... using simple_wmma_gemm kernel\n");
|
||||
simple_wmma_gemm<<<gridDim, blockDim>>>(A, B, C, D, M_GLOBAL, N_GLOBAL, K_GLOBAL, alpha, beta);
|
||||
#if CPU_DEBUG
|
||||
checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyDeviceToHost));
|
||||
#endif
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaEventRecord(stop));
|
||||
checkCudaErrors(cudaEventSynchronize(stop));
|
||||
|
||||
#if CPU_DEBUG
|
||||
printf("Verifying correctness of the computations...\n");
|
||||
|
||||
memcpy(result_host, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL);
|
||||
|
||||
matMultiplyOnHost(A_h, B_h, result_host, alpha, beta, M_GLOBAL, K_GLOBAL, K_GLOBAL, N_GLOBAL, M_GLOBAL, N_GLOBAL);
|
||||
|
||||
for (int i = 0; i < N_GLOBAL * M_GLOBAL; i++) {
|
||||
if (fabs(result_hD[i] - result_host[i]) > 0.1f)
|
||||
printf("mismatch i=%d result_hD=%f result_host=%f\n", i, result_hD[i], result_host[i]);
|
||||
}
|
||||
free(result_hD);
|
||||
free(result_host);
|
||||
#endif
|
||||
|
||||
float milliseconds = 0;
|
||||
|
||||
checkCudaErrors(cudaEventElapsedTime(&milliseconds, start, stop));
|
||||
|
||||
printf("Time: %f ms\n", milliseconds);
|
||||
printf("TFLOPS: %.2f\n",
|
||||
static_cast<double>((static_cast<double>(M_GLOBAL) * N_GLOBAL * K_GLOBAL * 2) / (milliseconds / 1000.))
|
||||
/ 1e12);
|
||||
|
||||
free(A_h);
|
||||
free(B_h);
|
||||
free(C_h);
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(A)));
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(B)));
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(C)));
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(D)));
|
||||
|
||||
return 0;
|
||||
}
|
||||
18
cpp/3_CUDA_Features/dmmaTensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/dmmaTensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/dmmaTensorCoreGemm/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/dmmaTensorCoreGemm/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
41
cpp/3_CUDA_Features/dmmaTensorCoreGemm/CMakeLists.txt
Normal file
41
cpp/3_CUDA_Features/dmmaTensorCoreGemm/CMakeLists.txt
Normal file
@@ -0,0 +1,41 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(dmmaTensorCoreGemm LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# This sample is not supported on QNX
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "QNX")
|
||||
message(STATUS "Will not build sample ${PROJECT_NAME} - not supported on QNX")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for dmmaTensorCoreGemm
|
||||
add_executable(dmmaTensorCoreGemm dmmaTensorCoreGemm.cu)
|
||||
|
||||
target_compile_options(dmmaTensorCoreGemm PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(dmmaTensorCoreGemm PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(dmmaTensorCoreGemm PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
36
cpp/3_CUDA_Features/dmmaTensorCoreGemm/README.md
Normal file
36
cpp/3_CUDA_Features/dmmaTensorCoreGemm/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# dmmaTensorCoreGemm - Double Precision Tensor Core GEMM
|
||||
|
||||
## Description
|
||||
|
||||
CUDA sample demonstrates double precision GEMM computation using the Double precision Warp Matrix Multiply and Accumulate (WMMA) API introduced with CUDA 11 in Ampere chip family tensor cores for faster matrix operations. This sample also uses async copy provided by cuda pipeline interface for gmem to shmem async loads which improves kernel performance and reduces register presssure. Further, this sample also demonstrates how to use cooperative groups async copy interface over a group for performing gmem to shmem async loads.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Matrix Multiply, WMMA, Tensor Cores
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, aarch64
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaFree, cudaGetErrorString, cudaGetLastError, cudaEventSynchronize, cudaFuncSetAttribute, cudaEventRecord, cudaMemset, cudaMalloc, cudaEventElapsedTime, cudaGetDeviceProperties, cudaEventCreate
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[C++11 CUDA](../../../README.md#c11-cuda)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
1042
cpp/3_CUDA_Features/dmmaTensorCoreGemm/dmmaTensorCoreGemm.cu
Normal file
1042
cpp/3_CUDA_Features/dmmaTensorCoreGemm/dmmaTensorCoreGemm.cu
Normal file
File diff suppressed because it is too large
Load Diff
18
cpp/3_CUDA_Features/globalToShmemAsyncCopy/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/globalToShmemAsyncCopy/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/globalToShmemAsyncCopy/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/globalToShmemAsyncCopy/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
41
cpp/3_CUDA_Features/globalToShmemAsyncCopy/CMakeLists.txt
Normal file
41
cpp/3_CUDA_Features/globalToShmemAsyncCopy/CMakeLists.txt
Normal file
@@ -0,0 +1,41 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(globalToShmemAsyncCopy LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# This sample is not supported on QNX
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "QNX")
|
||||
message(STATUS "Will not build sample ${PROJECT_NAME} - not supported on QNX")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# Source file
|
||||
# Add target for globalToShmemAsyncCopy
|
||||
add_executable(globalToShmemAsyncCopy globalToShmemAsyncCopy.cu)
|
||||
|
||||
target_compile_options(globalToShmemAsyncCopy PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(globalToShmemAsyncCopy PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(globalToShmemAsyncCopy PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
36
cpp/3_CUDA_Features/globalToShmemAsyncCopy/README.md
Normal file
36
cpp/3_CUDA_Features/globalToShmemAsyncCopy/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# globalToShmemAsyncCopy - Global Memory to Shared Memory Async Copy
|
||||
|
||||
## Description
|
||||
|
||||
This sample implements matrix multiplication which uses asynchronous copy of data from global to shared memory when on compute capability 8.0 or higher. Also demonstrates arrive-wait barrier for synchronization.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Runtime API, Linear Algebra, CPP11 CUDA
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows, QNX
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l, aarch64
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaStreamCreateWithFlags, cudaMalloc, cudaDeviceGetAttribute, cudaFree, cudaMallocHost, cudaEventSynchronize, cudaEventRecord, cudaFreeHost, cudaStreamSynchronize, cudaEventDestroy, cudaEventElapsedTime, cudaMemsetAsync, cudaMemcpyAsync, cudaEventCreate
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[C++11 CUDA](../../../README.md#c11-cuda)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## References (for more details)
|
||||
1028
cpp/3_CUDA_Features/globalToShmemAsyncCopy/globalToShmemAsyncCopy.cu
Normal file
1028
cpp/3_CUDA_Features/globalToShmemAsyncCopy/globalToShmemAsyncCopy.cu
Normal file
File diff suppressed because it is too large
Load Diff
18
cpp/3_CUDA_Features/graphConditionalNodes/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/graphConditionalNodes/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/graphConditionalNodes/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/graphConditionalNodes/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
34
cpp/3_CUDA_Features/graphConditionalNodes/CMakeLists.txt
Normal file
34
cpp/3_CUDA_Features/graphConditionalNodes/CMakeLists.txt
Normal file
@@ -0,0 +1,34 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(graphConditionalNodes LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for graphConditionalNodes
|
||||
add_executable(graphConditionalNodes graphConditionalNodes.cu)
|
||||
|
||||
target_compile_options(graphConditionalNodes PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(graphConditionalNodes PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(graphConditionalNodes PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
32
cpp/3_CUDA_Features/graphConditionalNodes/README.md
Normal file
32
cpp/3_CUDA_Features/graphConditionalNodes/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# graphConditionalNodes - Graph Conditional Nodes
|
||||
|
||||
## Description
|
||||
|
||||
A demonstration of CUDA graphs conditional nodes.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Graphs
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 6.0 ](https://developer.nvidia.com/cuda-gpus) [SM 6.1 ](https://developer.nvidia.com/cuda-gpus) [SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaDeviceSynchronize, cudaDriverGetVersion, cudaFree, cudaGraphAddNode, cudaGraphConditionalHandleCreate, cudaGraphCreate, cudaGraphDestroy, cudaGraphExecDestroy, cudaGraphInstantiate, cudaGraphLaunch, cudaGraphSetConditional, cudaMalloc, cudaMemset, cudaStreamBeginCapture, cudaStreamBeginCaptureToGraph, cudaStreamCreate, cudaStreamDestroy, cudaStreamEndCapture, cudaStreamGetCaptureInfo
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
|
||||
## References (for more details)
|
||||
@@ -0,0 +1,554 @@
|
||||
/* Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file demonstrates the usage of conditional graph nodes with
|
||||
* a series of *simple* example graphs.
|
||||
*
|
||||
* For more information on conditional nodes, see the programming guide:
|
||||
*
|
||||
* https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#conditional-graph-nodes
|
||||
*
|
||||
*/
|
||||
|
||||
// System includes
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
|
||||
// CUDA runtime
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
// helper functions and utilities to work with CUDA
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_functions.h>
|
||||
|
||||
/*
|
||||
* Create a graph containing two nodes.
|
||||
* The first node, A, is a kernel and the second node, B, is a conditional IF node.
|
||||
* The kernel sets the condition variable to true if a device memory location
|
||||
* contains an odd number. Otherwise the condition variable is set to false.
|
||||
* There is a single kernel, C, within the conditional body which prints a message.
|
||||
*
|
||||
* A -> B [ C ]
|
||||
*
|
||||
*/
|
||||
|
||||
__global__ void ifGraphKernelA(char *dPtr, cudaGraphConditionalHandle handle)
|
||||
{
|
||||
// In this example, condition is set if *dPtr is odd
|
||||
unsigned int value = *dPtr & 0x01;
|
||||
cudaGraphSetConditional(handle, value);
|
||||
printf("GPU: Handle set to %d\n", value);
|
||||
}
|
||||
|
||||
// This kernel will only be executed if the condition is true
|
||||
__global__ void ifGraphKernelC(void) { printf("GPU: Hello from the GPU! The condition was true.\n"); }
|
||||
|
||||
// Setup and launch the graph
|
||||
void simpleIfGraph(void)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphExec_t graphExec;
|
||||
cudaGraphNode_t kernelNode;
|
||||
cudaGraphNode_t conditionalNode;
|
||||
|
||||
void *kernelArgs[2];
|
||||
|
||||
// Allocate a byte of device memory to use as input
|
||||
char *dPtr;
|
||||
checkCudaErrors(cudaMalloc((void **)&dPtr, 1));
|
||||
|
||||
printf("simpleIfGraph: Building graph...\n");
|
||||
cudaGraphCreate(&graph, 0);
|
||||
|
||||
// Create conditional handle.
|
||||
cudaGraphConditionalHandle handle;
|
||||
cudaGraphConditionalHandleCreate(&handle, graph);
|
||||
|
||||
// Use a kernel upstream of the conditional to set the handle value
|
||||
cudaGraphNodeParams params = {cudaGraphNodeTypeKernel};
|
||||
params.kernel.func = (void *)ifGraphKernelA;
|
||||
params.kernel.blockDim.x = params.kernel.blockDim.y = params.kernel.blockDim.z = 1;
|
||||
params.kernel.gridDim.x = params.kernel.gridDim.y = params.kernel.gridDim.z = 1;
|
||||
params.kernel.kernelParams = kernelArgs;
|
||||
kernelArgs[0] = &dPtr;
|
||||
kernelArgs[1] = &handle;
|
||||
checkCudaErrors(cudaGraphAddNode(&kernelNode, graph, NULL, NULL, 0, ¶ms));
|
||||
|
||||
cudaGraphNodeParams cParams = {cudaGraphNodeTypeConditional};
|
||||
cParams.conditional.handle = handle;
|
||||
cParams.conditional.type = cudaGraphCondTypeIf;
|
||||
cParams.conditional.size = 1;
|
||||
checkCudaErrors(cudaGraphAddNode(&conditionalNode, graph, &kernelNode, NULL, 0, &cParams));
|
||||
|
||||
cudaGraph_t bodyGraph = cParams.conditional.phGraph_out[0];
|
||||
|
||||
// Populate the body of the conditional node
|
||||
cudaGraphNode_t bodyNode;
|
||||
params.kernel.func = (void *)ifGraphKernelC;
|
||||
params.kernel.kernelParams = nullptr;
|
||||
checkCudaErrors(cudaGraphAddNode(&bodyNode, bodyGraph, NULL, NULL, 0, ¶ms));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(&graphExec, graph, NULL, NULL, 0));
|
||||
|
||||
// Initialize device memory and launch the graph
|
||||
checkCudaErrors(cudaMemset(dPtr, 0, 1)); // Set dPtr to 0
|
||||
printf("Host: Launching graph with device memory set to 0\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Initialize device memory and launch the graph
|
||||
checkCudaErrors(cudaMemset(dPtr, 1, 1)); // Set dPtr to 1
|
||||
printf("Host: Launching graph with device memory set to 1\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Cleanup
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExec));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
checkCudaErrors(cudaFree(dPtr));
|
||||
|
||||
printf("simpleIfGraph: Complete\n\n");
|
||||
}
|
||||
|
||||
/*
|
||||
* Create a graph containing a single conditional while node.
|
||||
* The default value of the conditional variable is set to true, so this
|
||||
* effectively becomes a do-while loop as the conditional body will always
|
||||
* execute at least once. The body of the conditional contains 3 kernel nodes:
|
||||
* A [ B -> C -> D ]
|
||||
* Nodes B and C are just dummy nodes for demonstrative purposes. Node D
|
||||
* will decrement a device memory location and set the condition value to false
|
||||
* when the value reaches zero, terminating the loop.
|
||||
* In this example, stream capture is used to populate the conditional body.
|
||||
*/
|
||||
|
||||
// This kernel will only be executed if the condition is true
|
||||
__global__ void doWhileEmptyKernel(void)
|
||||
{
|
||||
printf("GPU: doWhileEmptyKernel()\n");
|
||||
return;
|
||||
}
|
||||
|
||||
__global__ void doWhileLoopKernel(char *dPtr, cudaGraphConditionalHandle handle)
|
||||
{
|
||||
if (--(*dPtr) == 0) {
|
||||
cudaGraphSetConditional(handle, 0);
|
||||
}
|
||||
printf("GPU: counter = %d\n", *dPtr);
|
||||
}
|
||||
|
||||
void simpleDoWhileGraph(void)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphExec_t graphExec;
|
||||
cudaGraphNode_t conditionalNode;
|
||||
|
||||
// Allocate a byte of device memory to use as input
|
||||
char *dPtr;
|
||||
checkCudaErrors(cudaMalloc((void **)&dPtr, 1));
|
||||
|
||||
printf("simpleDoWhileGraph: Building graph...\n");
|
||||
checkCudaErrors(cudaGraphCreate(&graph, 0));
|
||||
|
||||
cudaGraphConditionalHandle handle;
|
||||
checkCudaErrors(cudaGraphConditionalHandleCreate(&handle, graph, 1, cudaGraphCondAssignDefault));
|
||||
|
||||
cudaGraphNodeParams cParams = {cudaGraphNodeTypeConditional};
|
||||
cParams.conditional.handle = handle;
|
||||
cParams.conditional.type = cudaGraphCondTypeWhile;
|
||||
cParams.conditional.size = 1;
|
||||
checkCudaErrors(cudaGraphAddNode(&conditionalNode, graph, NULL, NULL, 0, &cParams));
|
||||
|
||||
cudaGraph_t bodyGraph = cParams.conditional.phGraph_out[0];
|
||||
|
||||
cudaStream_t captureStream;
|
||||
checkCudaErrors(cudaStreamCreate(&captureStream));
|
||||
|
||||
checkCudaErrors(
|
||||
cudaStreamBeginCaptureToGraph(captureStream, bodyGraph, nullptr, nullptr, 0, cudaStreamCaptureModeGlobal));
|
||||
doWhileEmptyKernel<<<1, 1, 0, captureStream>>>();
|
||||
doWhileEmptyKernel<<<1, 1, 0, captureStream>>>();
|
||||
doWhileLoopKernel<<<1, 1, 0, captureStream>>>(dPtr, handle);
|
||||
checkCudaErrors(cudaStreamEndCapture(captureStream, nullptr));
|
||||
checkCudaErrors(cudaStreamDestroy(captureStream));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(&graphExec, graph, NULL, NULL, 0));
|
||||
|
||||
// Initialize device memory and launch the graph
|
||||
checkCudaErrors(cudaMemset(dPtr, 10, 1)); // Set dPtr to 10
|
||||
printf("Host: Launching graph with loop counter set to 10\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Cleanup
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExec));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
checkCudaErrors(cudaFree(dPtr));
|
||||
|
||||
printf("simpleDoWhileGraph: Complete\n\n");
|
||||
}
|
||||
|
||||
/*
|
||||
* Create a graph containing a conditional while loop using stream capture.
|
||||
* This demonstrates how to insert a conditional node into a stream which is
|
||||
* being captured. The graph consists of a kernel node, A, followed by a
|
||||
* conditional while node, B, followed by a kernel node, D. The conditional
|
||||
* body is populated by a single kernel node, C:
|
||||
*
|
||||
* A -> B [ C ] -> D
|
||||
*
|
||||
* The same kernel will be used for both nodes A and C. This kernel will test
|
||||
* a device memory location and set the condition when the location is non-zero.
|
||||
* We must run the kernel before the loop as well as inside the loop in order
|
||||
* to behave like a while loop as opposed to a do-while loop. We need to evaluate
|
||||
* the device memory location before the conditional node is evaluated in order
|
||||
* to set the condition variable properly. Because we're using a kernel upstream
|
||||
* of the conditional node, there is no need to use the handle default value to
|
||||
* initialize the conditional value.
|
||||
*/
|
||||
|
||||
__global__ void capturedWhileKernel(char *dPtr, cudaGraphConditionalHandle handle)
|
||||
{
|
||||
printf("GPU: counter = %d\n", *dPtr);
|
||||
if (*dPtr) {
|
||||
(*dPtr)--;
|
||||
}
|
||||
cudaGraphSetConditional(handle, *dPtr);
|
||||
}
|
||||
|
||||
__global__ void capturedWhileEmptyKernel(void)
|
||||
{
|
||||
printf("GPU: capturedWhileEmptyKernel()\n");
|
||||
return;
|
||||
}
|
||||
|
||||
void capturedWhileGraph(void)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphExec_t graphExec;
|
||||
|
||||
cudaStreamCaptureStatus status;
|
||||
const cudaGraphNode_t *dependencies;
|
||||
size_t numDependencies;
|
||||
|
||||
// Allocate a byte of device memory to use as input
|
||||
char *dPtr;
|
||||
checkCudaErrors(cudaMalloc((void **)&dPtr, 1));
|
||||
|
||||
printf("capturedWhileGraph: Building graph...\n");
|
||||
cudaStream_t captureStream;
|
||||
checkCudaErrors(cudaStreamCreate(&captureStream));
|
||||
|
||||
checkCudaErrors(cudaStreamBeginCapture(captureStream, cudaStreamCaptureModeGlobal));
|
||||
|
||||
// Obtain the handle of the graph
|
||||
checkCudaErrors(
|
||||
cudaStreamGetCaptureInfo(captureStream, &status, NULL, &graph, &dependencies, NULL, &numDependencies));
|
||||
|
||||
// Create the conditional handle
|
||||
cudaGraphConditionalHandle handle;
|
||||
checkCudaErrors(cudaGraphConditionalHandleCreate(&handle, graph));
|
||||
|
||||
// Insert kernel node A
|
||||
capturedWhileKernel<<<1, 1, 0, captureStream>>>(dPtr, handle);
|
||||
|
||||
// Obtain the handle for node A
|
||||
checkCudaErrors(
|
||||
cudaStreamGetCaptureInfo(captureStream, &status, NULL, &graph, &dependencies, NULL, &numDependencies));
|
||||
|
||||
// Insert conditional node B
|
||||
cudaGraphNode_t conditionalNode;
|
||||
cudaGraphNodeParams cParams = {cudaGraphNodeTypeConditional};
|
||||
cParams.conditional.handle = handle;
|
||||
cParams.conditional.type = cudaGraphCondTypeWhile;
|
||||
cParams.conditional.size = 1;
|
||||
checkCudaErrors(cudaGraphAddNode(&conditionalNode, graph, dependencies, NULL, numDependencies, &cParams));
|
||||
|
||||
cudaGraph_t bodyGraph = cParams.conditional.phGraph_out[0];
|
||||
|
||||
// Update stream capture dependencies to account for the node we manually added
|
||||
checkCudaErrors(cudaStreamUpdateCaptureDependencies(
|
||||
captureStream, &conditionalNode, NULL, 1, cudaStreamSetCaptureDependencies));
|
||||
|
||||
// Insert kernel node D
|
||||
capturedWhileEmptyKernel<<<1, 1, 0, captureStream>>>();
|
||||
|
||||
checkCudaErrors(cudaStreamEndCapture(captureStream, &graph));
|
||||
checkCudaErrors(cudaStreamDestroy(captureStream));
|
||||
|
||||
// Populate conditional body graph using stream capture
|
||||
cudaStream_t bodyStream;
|
||||
checkCudaErrors(cudaStreamCreate(&bodyStream));
|
||||
|
||||
checkCudaErrors(
|
||||
cudaStreamBeginCaptureToGraph(bodyStream, bodyGraph, nullptr, nullptr, 0, cudaStreamCaptureModeGlobal));
|
||||
|
||||
// Insert kernel node C
|
||||
capturedWhileKernel<<<1, 1, 0, bodyStream>>>(dPtr, handle);
|
||||
checkCudaErrors(cudaStreamEndCapture(bodyStream, nullptr));
|
||||
checkCudaErrors(cudaStreamDestroy(bodyStream));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(&graphExec, graph, NULL, NULL, 0));
|
||||
|
||||
// Initialize device memory and launch the graph
|
||||
// Device memory is zero, so the conditional node will not execute
|
||||
checkCudaErrors(cudaMemset(dPtr, 0, 1)); // Set dPtr to 0
|
||||
printf("Host: Launching graph with loop counter set to 0\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Initialize device memory and launch the graph
|
||||
checkCudaErrors(cudaMemset(dPtr, 10, 1)); // Set dPtr to 10
|
||||
printf("Host: Launching graph with loop counter set to 10\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Cleanup
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExec));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
checkCudaErrors(cudaFree(dPtr));
|
||||
|
||||
printf("capturedWhileGraph: Complete\n\n");
|
||||
}
|
||||
|
||||
/*
|
||||
* Create a graph containing two nodes.
|
||||
* The first node, A, is a kernel and the second node, B, is a conditional IF node containing two graphs.
|
||||
* The first graph within the conditional will be executed when the condition is true, while the second
|
||||
* graph will be executed when the conditional is false.
|
||||
* The kernel sets the condition variable to true if a device memory location
|
||||
* contains an odd number. Otherwise the condition variable is set to false.
|
||||
* There is a single kernel(C & D) within each conditional body which prints a message.
|
||||
*
|
||||
* A -> B [ C | D ]
|
||||
*
|
||||
* This example requires CUDA >= 12.8.
|
||||
*/
|
||||
|
||||
// This kernel will only be executed if the condition is false
|
||||
__global__ void ifGraphKernelD(void) { printf("GPU: Hello from the GPU! The condition was false.\n"); }
|
||||
|
||||
// Setup and launch the graph
|
||||
void simpleIfElseGraph(void)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphExec_t graphExec;
|
||||
cudaGraphNode_t kernelNode;
|
||||
cudaGraphNode_t conditionalNode;
|
||||
|
||||
void *kernelArgs[2];
|
||||
|
||||
// Allocate a byte of device memory to use as input
|
||||
char *dPtr;
|
||||
checkCudaErrors(cudaMalloc((void **)&dPtr, 1));
|
||||
|
||||
printf("simpleIfElseGraph: Building graph...\n");
|
||||
cudaGraphCreate(&graph, 0);
|
||||
|
||||
// Create conditional handle.
|
||||
cudaGraphConditionalHandle handle;
|
||||
cudaGraphConditionalHandleCreate(&handle, graph);
|
||||
|
||||
// Use a kernel upstream of the conditional to set the handle value
|
||||
cudaGraphNodeParams params = {cudaGraphNodeTypeKernel};
|
||||
params.kernel.func = (void *)ifGraphKernelA;
|
||||
params.kernel.blockDim.x = params.kernel.blockDim.y = params.kernel.blockDim.z = 1;
|
||||
params.kernel.gridDim.x = params.kernel.gridDim.y = params.kernel.gridDim.z = 1;
|
||||
params.kernel.kernelParams = kernelArgs;
|
||||
kernelArgs[0] = &dPtr;
|
||||
kernelArgs[1] = &handle;
|
||||
checkCudaErrors(cudaGraphAddNode(&kernelNode, graph, NULL, NULL, 0, ¶ms));
|
||||
|
||||
cudaGraphNodeParams cParams = {cudaGraphNodeTypeConditional};
|
||||
cParams.conditional.handle = handle;
|
||||
cParams.conditional.type = cudaGraphCondTypeIf;
|
||||
cParams.conditional.size = 2; // Set size to 2 to indicate an ELSE graph will be used
|
||||
checkCudaErrors(cudaGraphAddNode(&conditionalNode, graph, &kernelNode, NULL, 0, &cParams));
|
||||
|
||||
cudaGraph_t bodyGraph = cParams.conditional.phGraph_out[0];
|
||||
|
||||
// Populate the body of the first graph in the conditional node, executed if the condition is true
|
||||
cudaGraphNode_t trueBodyNode;
|
||||
params.kernel.func = (void *)ifGraphKernelC;
|
||||
params.kernel.kernelParams = nullptr;
|
||||
checkCudaErrors(cudaGraphAddNode(&trueBodyNode, bodyGraph, NULL, NULL, 0, ¶ms));
|
||||
|
||||
// Populate the body of the second graph in the conditional node, executed if the condition is false
|
||||
bodyGraph = cParams.conditional.phGraph_out[1];
|
||||
|
||||
cudaGraphNode_t falseBodyNode;
|
||||
params.kernel.func = (void *)ifGraphKernelD;
|
||||
params.kernel.kernelParams = nullptr;
|
||||
checkCudaErrors(cudaGraphAddNode(&falseBodyNode, bodyGraph, NULL, NULL, 0, ¶ms));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(&graphExec, graph, NULL, NULL, 0));
|
||||
|
||||
// Initialize device memory and launch the graph
|
||||
checkCudaErrors(cudaMemset(dPtr, 0, 1)); // Set dPtr to 0
|
||||
printf("Host: Launching graph with device memory set to 0\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Initialize device memory and launch the graph
|
||||
checkCudaErrors(cudaMemset(dPtr, 1, 1)); // Set dPtr to 1
|
||||
printf("Host: Launching graph with device memory set to 1\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
|
||||
// Cleanup
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExec));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
checkCudaErrors(cudaFree(dPtr));
|
||||
|
||||
printf("simpleIfElseGraph: Complete\n\n");
|
||||
}
|
||||
|
||||
/*
|
||||
* Create a graph containing two nodes.
|
||||
* The first node, A, is a kernel and the second node, B, is a conditional SWITCH node containing four graphs.
|
||||
* The nth graph within the conditional will be executed when the condition is n. If conditional >= n,
|
||||
* no graph will be executed.
|
||||
* Kernel A sets the condition variable to the value stored in a device memory location.
|
||||
* This device location is updated from the host with each launch to demonstrate the behavior.
|
||||
* There is a single kernel(nodes C, D, E and F) within each conditional body which prints a message.
|
||||
*
|
||||
* A -> B [ C | D | E | F ]
|
||||
*
|
||||
* This example requires CUDA >= 12.8.
|
||||
*/
|
||||
|
||||
__global__ void switchGraphKernelA(char *dPtr, cudaGraphConditionalHandle handle)
|
||||
{
|
||||
unsigned int value = *dPtr;
|
||||
cudaGraphSetConditional(handle, value);
|
||||
printf("GPU: Handle set to %d\n", value);
|
||||
}
|
||||
|
||||
__global__ void switchGraphKernelC(void) { printf("GPU: Hello from switchGraphKernelC(), running on the GPU!\n"); }
|
||||
|
||||
__global__ void switchGraphKernelD(void) { printf("GPU: Hello from switchGraphKernelD(), running on the GPU!\n"); }
|
||||
|
||||
__global__ void switchGraphKernelE(void) { printf("GPU: Hello from switchGraphKernelE(), running on the GPU!\n"); }
|
||||
|
||||
__global__ void switchGraphKernelF(void) { printf("GPU: Hello from switchGraphKernelF(), running on the GPU!\n"); }
|
||||
|
||||
// Setup and launch the graph
|
||||
void simpleSwitchGraph(void)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphExec_t graphExec;
|
||||
cudaGraphNode_t kernelNode;
|
||||
cudaGraphNode_t conditionalNode;
|
||||
|
||||
void *kernelArgs[2];
|
||||
|
||||
// Allocate a byte of device memory to use as input
|
||||
char *dPtr;
|
||||
checkCudaErrors(cudaMalloc((void **)&dPtr, 1));
|
||||
|
||||
printf("simpleSwitchGraph: Building graph...\n");
|
||||
cudaGraphCreate(&graph, 0);
|
||||
|
||||
// Create conditional handle.
|
||||
cudaGraphConditionalHandle handle;
|
||||
cudaGraphConditionalHandleCreate(&handle, graph);
|
||||
|
||||
// Use a kernel upstream of the conditional to set the handle value
|
||||
cudaGraphNodeParams params = {cudaGraphNodeTypeKernel};
|
||||
params.kernel.func = (void *)switchGraphKernelA;
|
||||
params.kernel.blockDim.x = params.kernel.blockDim.y = params.kernel.blockDim.z = 1;
|
||||
params.kernel.gridDim.x = params.kernel.gridDim.y = params.kernel.gridDim.z = 1;
|
||||
params.kernel.kernelParams = kernelArgs;
|
||||
kernelArgs[0] = &dPtr;
|
||||
kernelArgs[1] = &handle;
|
||||
checkCudaErrors(cudaGraphAddNode(&kernelNode, graph, NULL, NULL, 0, ¶ms));
|
||||
|
||||
cudaGraphNodeParams cParams = {cudaGraphNodeTypeConditional};
|
||||
cParams.conditional.handle = handle;
|
||||
cParams.conditional.type = cudaGraphCondTypeSwitch;
|
||||
cParams.conditional.size = 4;
|
||||
checkCudaErrors(cudaGraphAddNode(&conditionalNode, graph, &kernelNode, NULL, 0, &cParams));
|
||||
|
||||
// Populate the four graph bodies within the SWITCH conditional graph
|
||||
cudaGraphNode_t bodyNode;
|
||||
params.kernel.kernelParams = nullptr;
|
||||
params.kernel.func = (void *)switchGraphKernelC;
|
||||
checkCudaErrors(cudaGraphAddNode(&bodyNode, cParams.conditional.phGraph_out[0], NULL, NULL, 0, ¶ms));
|
||||
params.kernel.func = (void *)switchGraphKernelD;
|
||||
checkCudaErrors(cudaGraphAddNode(&bodyNode, cParams.conditional.phGraph_out[1], NULL, NULL, 0, ¶ms));
|
||||
params.kernel.func = (void *)switchGraphKernelE;
|
||||
checkCudaErrors(cudaGraphAddNode(&bodyNode, cParams.conditional.phGraph_out[2], NULL, NULL, 0, ¶ms));
|
||||
params.kernel.func = (void *)switchGraphKernelF;
|
||||
checkCudaErrors(cudaGraphAddNode(&bodyNode, cParams.conditional.phGraph_out[3], NULL, NULL, 0, ¶ms));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(&graphExec, graph, NULL, NULL, 0));
|
||||
|
||||
for (char i = 0; i < 5; i++) {
|
||||
// Initialize device memory and launch the graph
|
||||
checkCudaErrors(cudaMemset(dPtr, i, 1));
|
||||
printf("Host: Launching graph with device memory set to %d\n", i);
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, 0));
|
||||
checkCudaErrors(cudaDeviceSynchronize());
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExec));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
checkCudaErrors(cudaFree(dPtr));
|
||||
|
||||
printf("simpleSwitchGraph: Complete\n\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int device = findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
int driverVersion = 0;
|
||||
|
||||
cudaDriverGetVersion(&driverVersion);
|
||||
printf("Driver version is: %d.%d\n", driverVersion / 1000, (driverVersion % 100) / 10);
|
||||
|
||||
if (driverVersion < 12030) {
|
||||
printf("Skipping execution as driver does not support Graph Conditional Nodes\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
simpleIfGraph();
|
||||
simpleDoWhileGraph();
|
||||
capturedWhileGraph();
|
||||
|
||||
if (driverVersion < 12080) {
|
||||
printf("Skipping execution as driver does not support if/else and switch type Graph Conditional Nodes\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
simpleIfElseGraph();
|
||||
simpleSwitchGraph();
|
||||
|
||||
return 0;
|
||||
}
|
||||
18
cpp/3_CUDA_Features/graphMemoryFootprint/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/graphMemoryFootprint/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/graphMemoryFootprint/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/graphMemoryFootprint/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
34
cpp/3_CUDA_Features/graphMemoryFootprint/CMakeLists.txt
Normal file
34
cpp/3_CUDA_Features/graphMemoryFootprint/CMakeLists.txt
Normal file
@@ -0,0 +1,34 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(graphMemoryFootprint LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for graphMemoryFootprint
|
||||
add_executable(graphMemoryFootprint graphMemoryFootprint.cu)
|
||||
|
||||
target_compile_options(graphMemoryFootprint PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(graphMemoryFootprint PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(graphMemoryFootprint PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
32
cpp/3_CUDA_Features/graphMemoryFootprint/README.md
Normal file
32
cpp/3_CUDA_Features/graphMemoryFootprint/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# graphMemoryFootprint - Graph Memory Footprint
|
||||
|
||||
## Description
|
||||
|
||||
This sample demonstrates how graph memory nodes re-use virtual addresses and physical memory.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Runtime API, Performance Strategies, CUDA Graphs
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 6.0 ](https://developer.nvidia.com/cuda-gpus) [SM 6.1 ](https://developer.nvidia.com/cuda-gpus) [SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaGraphAddMemAllocNode, cudaStreamCreateWithFlags, cudaGraphInstantiate, cudaStreamDestroy, cudaFree, cudaDeviceGetAttribute, cudaGraphAddKernelNode, cudaGraphAddMemFreeNode, cudaDeviceGetGraphMemAttribute, cudaGraphCreate, cudaGraphDestroy, cudaDriverGetVersion, cudaGraphLaunch, cudaStreamSynchronize, cudaDeviceGraphMemTrim, cudaGetDeviceProperties, cudaGraphExecDestroy
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
|
||||
## References (for more details)
|
||||
390
cpp/3_CUDA_Features/graphMemoryFootprint/graphMemoryFootprint.cu
Normal file
390
cpp/3_CUDA_Features/graphMemoryFootprint/graphMemoryFootprint.cu
Normal file
@@ -0,0 +1,390 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// System includes
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// helper functions and utilities to work with CUDA
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_functions.h>
|
||||
|
||||
#define NUM_GRAPHS 8
|
||||
#define THREADS_PER_BLOCK 512
|
||||
|
||||
void printMemoryFootprint(int device)
|
||||
{
|
||||
size_t footprint;
|
||||
checkCudaErrors(cudaDeviceGetGraphMemAttribute(device, (cudaGraphMemAttributeType)0, &footprint));
|
||||
printf(" FOOTPRINT: %lu bytes\n", footprint);
|
||||
}
|
||||
|
||||
void prepareAllocParams(cudaMemAllocNodeParams *allocParams, size_t bytes, int device)
|
||||
{
|
||||
memset(allocParams, 0, sizeof(*allocParams));
|
||||
|
||||
allocParams->bytesize = bytes;
|
||||
allocParams->poolProps.allocType = cudaMemAllocationTypePinned;
|
||||
allocParams->poolProps.location.id = device;
|
||||
allocParams->poolProps.location.type = cudaMemLocationTypeDevice;
|
||||
}
|
||||
|
||||
void createVirtAddrReuseGraph(cudaGraphExec_t *graphExec, size_t bytes, int device)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphNode_t allocNodeA, allocNodeB, freeNodeA, freeNodeB;
|
||||
cudaMemAllocNodeParams allocParams;
|
||||
float *d_a, *d_b;
|
||||
|
||||
checkCudaErrors(cudaGraphCreate(&graph, 0));
|
||||
prepareAllocParams(&allocParams, bytes, device);
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemAllocNode(&allocNodeA, graph, NULL, 0, &allocParams));
|
||||
d_a = (float *)allocParams.dptr;
|
||||
checkCudaErrors(cudaGraphAddMemFreeNode(&freeNodeA, graph, &allocNodeA, 1, (void *)d_a));
|
||||
|
||||
// The dependency between the allocation of d_b and the free of d_a allows d_b
|
||||
// to reuse the same VA.
|
||||
checkCudaErrors(cudaGraphAddMemAllocNode(&allocNodeB, graph, &freeNodeA, 1, &allocParams));
|
||||
d_b = (float *)allocParams.dptr;
|
||||
|
||||
if (d_a == d_b) {
|
||||
printf("Check confirms that d_a and d_b share a virtual address.\n");
|
||||
}
|
||||
else {
|
||||
printf("Check shows that d_a and d_b DO NOT share a virtual address.\n");
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemFreeNode(&freeNodeB, graph, &allocNodeB, 1, (void *)d_b));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(graphExec, graph, NULL, NULL, 0));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
}
|
||||
|
||||
void virtualAddressReuseSingleGraph(size_t bytes, int device)
|
||||
{
|
||||
cudaStream_t stream;
|
||||
cudaGraphExec_t graphExec;
|
||||
|
||||
printf("================================\n");
|
||||
printf("Running virtual address reuse example.\n");
|
||||
printf("Sequential allocations & frees within a single graph enable CUDA to "
|
||||
"reuse virtual addresses.\n\n");
|
||||
|
||||
createVirtAddrReuseGraph(&graphExec, bytes, device);
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
|
||||
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, stream));
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
printMemoryFootprint(device);
|
||||
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExec));
|
||||
checkCudaErrors(cudaStreamDestroy(stream));
|
||||
}
|
||||
|
||||
// This is a kernel that does no real work but runs at least for a specified
|
||||
// number of clocks
|
||||
__global__ void clockBlock(clock_t clock_count)
|
||||
{
|
||||
unsigned int start_clock = (unsigned int)clock();
|
||||
|
||||
clock_t clock_offset = 0;
|
||||
|
||||
while (clock_offset < clock_count) {
|
||||
unsigned int end_clock = (unsigned int)clock();
|
||||
|
||||
// The code below should work like
|
||||
// this (thanks to modular arithmetics):
|
||||
//
|
||||
// clock_offset = (clock_t) (end_clock > start_clock ?
|
||||
// end_clock - start_clock :
|
||||
// end_clock + (0xffffffffu - start_clock));
|
||||
//
|
||||
// Indeed, let m = 2^32 then
|
||||
// end - start = end + m - start (mod m).
|
||||
|
||||
clock_offset = (clock_t)(end_clock - start_clock);
|
||||
}
|
||||
}
|
||||
|
||||
// A pointer to the allocated device buffer is returned in dPtr so the caller
|
||||
// can compare virtual addresses. The kernel node is added to increase the
|
||||
// graph's runtime.
|
||||
void createSimpleAllocFreeGraph(cudaGraphExec_t *graphExec, float **dPtr, size_t bytes, int device)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphNode_t allocNodeA, freeNodeA, blockDeviceNode;
|
||||
cudaMemAllocNodeParams allocParams;
|
||||
cudaKernelNodeParams blockDeviceNodeParams = {0};
|
||||
int numElements = bytes / sizeof(float);
|
||||
float kernelTime = 5; // time for each thread to run in microseconds
|
||||
|
||||
checkCudaErrors(cudaGraphCreate(&graph, 0));
|
||||
prepareAllocParams(&allocParams, bytes, device);
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemAllocNode(&allocNodeA, graph, NULL, 0, &allocParams));
|
||||
*dPtr = (float *)allocParams.dptr;
|
||||
|
||||
int clockRate;
|
||||
checkCudaErrors(cudaDeviceGetAttribute(&clockRate, cudaDevAttrClockRate, device));
|
||||
clock_t time_clocks = (clock_t)((kernelTime / 1000.0) * clockRate);
|
||||
|
||||
void *blockDeviceArgs[1] = {(void *)&time_clocks};
|
||||
|
||||
size_t numBlocks = numElements / (size_t)THREADS_PER_BLOCK;
|
||||
blockDeviceNodeParams.gridDim = dim3(numBlocks, 1, 1);
|
||||
blockDeviceNodeParams.blockDim = dim3(THREADS_PER_BLOCK, 1, 1);
|
||||
blockDeviceNodeParams.sharedMemBytes = 0;
|
||||
blockDeviceNodeParams.extra = NULL;
|
||||
blockDeviceNodeParams.func = (void *)clockBlock;
|
||||
blockDeviceNodeParams.kernelParams = (void **)blockDeviceArgs;
|
||||
checkCudaErrors(cudaGraphAddKernelNode(&blockDeviceNode, graph, &allocNodeA, 1, &blockDeviceNodeParams));
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemFreeNode(&freeNodeA, graph, &blockDeviceNode, 1, (void *)*dPtr));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(graphExec, graph, NULL, NULL, 0));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
}
|
||||
|
||||
void physicalMemoryReuseSingleStream(size_t bytes, int device)
|
||||
{
|
||||
cudaStream_t stream;
|
||||
cudaGraphExec_t graphExecs[NUM_GRAPHS];
|
||||
float *dPtrs[NUM_GRAPHS];
|
||||
bool virtualAddrDiffer = true;
|
||||
|
||||
printf("================================\n");
|
||||
printf("Running physical memory reuse example.\n");
|
||||
printf("CUDA reuses the same physical memory for allocations from separate "
|
||||
"graphs when the allocation lifetimes don't overlap.\n\n");
|
||||
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
createSimpleAllocFreeGraph(&graphExecs[i], &dPtrs[i], bytes, device);
|
||||
}
|
||||
|
||||
printf("Creating the graph execs does not reserve any physical memory.\n");
|
||||
printMemoryFootprint(device);
|
||||
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
|
||||
|
||||
checkCudaErrors(cudaGraphLaunch(graphExecs[0], stream));
|
||||
printf("\nThe first graph launched reserves the memory it needs.\n");
|
||||
printMemoryFootprint(device);
|
||||
|
||||
checkCudaErrors(cudaGraphLaunch(graphExecs[0], stream));
|
||||
printf("A subsequent launch of the same graph in the same stream reuses the "
|
||||
"same physical memory. ");
|
||||
printf("Thus the memory footprint does not grow here.\n");
|
||||
printMemoryFootprint(device);
|
||||
|
||||
printf("\nSubsequent launches of other graphs in the same stream also reuse the "
|
||||
"physical memory. ");
|
||||
printf("Thus the memory footprint does not grow here.\n");
|
||||
for (int i = 1; i < NUM_GRAPHS; i++) {
|
||||
checkCudaErrors(cudaGraphLaunch(graphExecs[i], stream));
|
||||
printf("%02d: ", i);
|
||||
printMemoryFootprint(device);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
for (int j = i + 1; j < NUM_GRAPHS; j++) {
|
||||
if (dPtrs[i] == dPtrs[j]) {
|
||||
virtualAddrDiffer = false;
|
||||
printf("Error: Graph exec %d and %d have the same virtual address!\n", i - 1, i);
|
||||
}
|
||||
}
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExecs[i]));
|
||||
}
|
||||
if (virtualAddrDiffer) {
|
||||
printf("\nCheck confirms all graphs use a different virtual address.\n");
|
||||
}
|
||||
else {
|
||||
printf("\nAll graphs do NOT use different virtual addresses. Exiting test.\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaStreamDestroy(stream));
|
||||
}
|
||||
|
||||
void simultaneousStreams(size_t bytes, int device)
|
||||
{
|
||||
cudaStream_t streams[NUM_GRAPHS];
|
||||
cudaGraphExec_t graphExecs[NUM_GRAPHS];
|
||||
float *dPtrs[NUM_GRAPHS];
|
||||
|
||||
printf("================================\n");
|
||||
printf("Running simultaneous streams example.\n");
|
||||
printf("Graphs that can run concurrently need separate physical memory. ");
|
||||
printf("In this example, each graph launched in a separate stream increases the "
|
||||
"total memory footprint.\n\n");
|
||||
|
||||
printf("When launching a new graph, CUDA may reuse physical memory from a graph "
|
||||
"whose execution has already ");
|
||||
printf("finished -- even if the new graph is being launched in a different "
|
||||
"stream from the completed graph. ");
|
||||
printf("Therefore, a kernel node is added to the graphs to increase "
|
||||
"runtime.\n\n");
|
||||
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
createSimpleAllocFreeGraph(&graphExecs[i], &dPtrs[i], bytes, device);
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&streams[i], cudaStreamNonBlocking));
|
||||
}
|
||||
|
||||
printf("Initial footprint:\n");
|
||||
printMemoryFootprint(device);
|
||||
|
||||
printf("\nEach graph launch in a seperate stream grows the memory footprint:\n");
|
||||
for (int i = 1; i < NUM_GRAPHS; i++) {
|
||||
checkCudaErrors(cudaGraphLaunch(graphExecs[i], streams[i]));
|
||||
printf("%02d: ", i);
|
||||
printMemoryFootprint(device);
|
||||
}
|
||||
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
checkCudaErrors(cudaStreamSynchronize(streams[i]));
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExecs[i]));
|
||||
checkCudaErrors(cudaStreamDestroy(streams[i]));
|
||||
}
|
||||
}
|
||||
|
||||
void createSimpleAllocNoFreeGraph(cudaGraphExec_t *graphExec, float **dPtr, size_t bytes, int device)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphNode_t allocNodeA;
|
||||
cudaMemAllocNodeParams allocParams;
|
||||
|
||||
checkCudaErrors(cudaGraphCreate(&graph, 0));
|
||||
prepareAllocParams(&allocParams, bytes, device);
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemAllocNode(&allocNodeA, graph, NULL, 0, &allocParams));
|
||||
*dPtr = (float *)allocParams.dptr;
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(graphExec, graph, NULL, NULL, 0));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
}
|
||||
|
||||
void unfreedAllocations(size_t bytes, int device)
|
||||
{
|
||||
cudaStream_t stream;
|
||||
cudaGraphExec_t graphExecs[NUM_GRAPHS];
|
||||
float *dPtrs[NUM_GRAPHS];
|
||||
|
||||
printf("================================\n");
|
||||
printf("Running unfreed streams example.\n");
|
||||
printf("CUDA cannot reuse phyiscal memory from graphs which do not free their "
|
||||
"allocations.\n\n");
|
||||
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
createSimpleAllocNoFreeGraph(&graphExecs[i], &dPtrs[i], bytes, device);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
|
||||
|
||||
printf("Despite being launched in the same stream, each graph launch grows the "
|
||||
"memory footprint. ");
|
||||
printf("Since the allocation is not freed, CUDA keeps the memory valid for "
|
||||
"use.\n");
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
checkCudaErrors(cudaGraphLaunch(graphExecs[i], stream));
|
||||
printf("%02d: ", i);
|
||||
printMemoryFootprint(device);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
|
||||
checkCudaErrors(cudaDeviceGraphMemTrim(device));
|
||||
printf("\nTrimming does not impact the memory footprint since the un-freed "
|
||||
"allocations are still holding onto the memory.\n");
|
||||
printMemoryFootprint(device);
|
||||
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
checkCudaErrors(cudaFree(dPtrs[i]));
|
||||
}
|
||||
printf("\nFreeing the allocations does not shrink the footprint.\n");
|
||||
printMemoryFootprint(device);
|
||||
|
||||
checkCudaErrors(cudaDeviceGraphMemTrim(device));
|
||||
printf("\nSince the allocations are now freed, trimming does reduce the "
|
||||
"footprint even when the graph execs are not yet destroyed.\n");
|
||||
printMemoryFootprint(device);
|
||||
|
||||
for (int i = 0; i < NUM_GRAPHS; i++) {
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExecs[i]));
|
||||
}
|
||||
checkCudaErrors(cudaStreamDestroy(stream));
|
||||
}
|
||||
|
||||
void cleanupMemory(int device)
|
||||
{
|
||||
checkCudaErrors(cudaDeviceGraphMemTrim(device));
|
||||
printf("\nCleaning up example by trimming device memory.\n");
|
||||
printMemoryFootprint(device);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
size_t bytes = 64 * 1024 * 1024;
|
||||
int device = findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
int driverVersion = 0;
|
||||
int deviceSupportsMemoryPools = 0;
|
||||
|
||||
cudaDriverGetVersion(&driverVersion);
|
||||
printf("Driver version is: %d.%d\n", driverVersion / 1000, (driverVersion % 100) / 10);
|
||||
|
||||
if (driverVersion < 11040) {
|
||||
printf("Waiving execution as driver does not support Graph Memory Nodes\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
cudaDeviceGetAttribute(&deviceSupportsMemoryPools, cudaDevAttrMemoryPoolsSupported, device);
|
||||
if (!deviceSupportsMemoryPools) {
|
||||
printf("Waiving execution as device does not support Memory Pools\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
else {
|
||||
printf("Running sample.\n");
|
||||
}
|
||||
|
||||
virtualAddressReuseSingleGraph(bytes, device);
|
||||
cleanupMemory(device);
|
||||
|
||||
physicalMemoryReuseSingleStream(bytes, device);
|
||||
cleanupMemory(device);
|
||||
|
||||
simultaneousStreams(bytes, device);
|
||||
cleanupMemory(device);
|
||||
|
||||
unfreedAllocations(bytes, device);
|
||||
cleanupMemory(device);
|
||||
|
||||
printf("================================\n");
|
||||
printf("Sample complete.\n");
|
||||
}
|
||||
18
cpp/3_CUDA_Features/graphMemoryNodes/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/graphMemoryNodes/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/graphMemoryNodes/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/graphMemoryNodes/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
34
cpp/3_CUDA_Features/graphMemoryNodes/CMakeLists.txt
Normal file
34
cpp/3_CUDA_Features/graphMemoryNodes/CMakeLists.txt
Normal file
@@ -0,0 +1,34 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(graphMemoryNodes LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for graphMemoryNodes
|
||||
add_executable(graphMemoryNodes graphMemoryNodes.cu)
|
||||
|
||||
target_compile_options(graphMemoryNodes PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(graphMemoryNodes PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(graphMemoryNodes PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
32
cpp/3_CUDA_Features/graphMemoryNodes/README.md
Normal file
32
cpp/3_CUDA_Features/graphMemoryNodes/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# graphMemoryNodes - Graph Memory Nodes
|
||||
|
||||
## Description
|
||||
|
||||
A demonstration of memory allocations and frees within CUDA graphs using Graph APIs and Stream Capture APIs.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
CUDA Graphs, Stream Capture
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 6.0 ](https://developer.nvidia.com/cuda-gpus) [SM 6.1 ](https://developer.nvidia.com/cuda-gpus) [SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaDeviceGetAttribute, cudaDriverGetVersion, cudaGraphLaunch, cudaEventDestroy, cudaMallocAsync, cudaStreamEndCapture, cudaMallocManaged, cudaGraphCreate, cudaMemcpyAsync, cudaFreeAsync, cudaStreamCreateWithFlags, cudaGraphInstantiate, cudaStreamDestroy, cudaStreamBeginCapture, cudaStreamWaitEvent, cudaEventCreate, cudaGraphAddMemAllocNode, cudaFree, cudaGraphAddKernelNode, cudaGraphAddMemFreeNode, cudaGraphDestroy, cudaEventRecord, cudaStreamSynchronize, cudaMalloc, cudaGraphExecDestroy
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
|
||||
## References (for more details)
|
||||
555
cpp/3_CUDA_Features/graphMemoryNodes/graphMemoryNodes.cu
Normal file
555
cpp/3_CUDA_Features/graphMemoryNodes/graphMemoryNodes.cu
Normal file
@@ -0,0 +1,555 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// System includes
|
||||
#include <assert.h>
|
||||
#include <climits>
|
||||
#include <stdio.h>
|
||||
#include <vector>
|
||||
|
||||
// CUDA runtime
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
// helper functions and utilities to work with CUDA
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_functions.h>
|
||||
|
||||
#define THREADS_PER_BLOCK 512
|
||||
#define ALLOWABLE_VARIANCE 1.e-6f
|
||||
#define NUM_ELEMENTS 8000000
|
||||
|
||||
// Stores the square of each input element in output array
|
||||
__global__ void squareArray(const float *input, float *output, int numElements)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
|
||||
if (idx < numElements) {
|
||||
output[idx] = input[idx] * input[idx];
|
||||
}
|
||||
}
|
||||
|
||||
// Stores the negative of each input element in output array
|
||||
__global__ void negateArray(const float *input, float *output, int numElements)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
|
||||
if (idx < numElements) {
|
||||
output[idx] = input[idx] * -1;
|
||||
}
|
||||
}
|
||||
|
||||
struct negSquareArrays
|
||||
{
|
||||
float *input;
|
||||
float *square;
|
||||
float *negSquare;
|
||||
int numElements;
|
||||
size_t bytes;
|
||||
size_t numBlocks;
|
||||
};
|
||||
|
||||
void fillRandomly(float *array, int numElements)
|
||||
{
|
||||
for (int n = 0; n < numElements; n++) {
|
||||
array[n] = rand() / (float)RAND_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
void resetOutputArrays(negSquareArrays *hostArrays)
|
||||
{
|
||||
fillRandomly(hostArrays->square, hostArrays->numElements);
|
||||
fillRandomly(hostArrays->negSquare, hostArrays->numElements);
|
||||
}
|
||||
|
||||
void prepareHostArrays(negSquareArrays *hostArrays)
|
||||
{
|
||||
hostArrays->numElements = NUM_ELEMENTS;
|
||||
size_t bytes = hostArrays->numElements * sizeof(float);
|
||||
|
||||
size_t numBlocks = hostArrays->numElements / (size_t)THREADS_PER_BLOCK;
|
||||
if ((numBlocks % (size_t)THREADS_PER_BLOCK) != 0) {
|
||||
numBlocks++;
|
||||
}
|
||||
|
||||
hostArrays->input = (float *)malloc(bytes);
|
||||
hostArrays->square = (float *)malloc(bytes);
|
||||
hostArrays->negSquare = (float *)malloc(bytes);
|
||||
hostArrays->bytes = bytes;
|
||||
hostArrays->numBlocks = numBlocks;
|
||||
|
||||
fillRandomly(hostArrays->input, hostArrays->numElements);
|
||||
fillRandomly(hostArrays->square, hostArrays->numElements);
|
||||
fillRandomly(hostArrays->negSquare, hostArrays->numElements);
|
||||
}
|
||||
|
||||
void createFreeGraph(cudaGraphExec_t *graphExec, float *dPtr)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaGraphNode_t freeNode;
|
||||
|
||||
checkCudaErrors(cudaGraphCreate(&graph, 0));
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemFreeNode(&freeNode, graph, NULL, 0, (void *)dPtr));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(graphExec, graph, NULL, NULL, 0));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates explicitly creating a CUDA graph including memory nodes.
|
||||
* createNegateSquaresGraphWithStreamCapture constructs an equivalent graph
|
||||
* using stream capture.
|
||||
*
|
||||
* If d_negSquare_out is non null, then:
|
||||
* 1) d_negSquare will not be freed;
|
||||
* 2) the value of d_negSquare_out will be set to d_negSquare.
|
||||
*
|
||||
* Diagram of the graph constructed by createNegateSquaresGraphExplicitly:
|
||||
*
|
||||
* alloc d_input
|
||||
* |
|
||||
* alloc d_square
|
||||
* |
|
||||
* Memcpy a to device
|
||||
* |
|
||||
* launch kernel squareArray ------->---- Memcpy d_square to host
|
||||
* | |
|
||||
* free d_input |
|
||||
* | |
|
||||
* allocate d_negSquare |
|
||||
* | |
|
||||
* launch kernel negateArray -------->--- free d_square
|
||||
* |
|
||||
* Memcpy d_negSquare to host
|
||||
* |
|
||||
* free d_negSquare
|
||||
*/
|
||||
void createNegateSquaresGraphExplicitly(cudaGraphExec_t *graphExec,
|
||||
int device,
|
||||
negSquareArrays *hostArrays,
|
||||
float **d_negSquare_out = NULL)
|
||||
{
|
||||
// Array buffers on device
|
||||
float *d_input, *d_square, *d_negSquare;
|
||||
|
||||
// Memory allocation parameters
|
||||
cudaMemAllocNodeParams allocParams;
|
||||
memset(&allocParams, 0, sizeof(allocParams));
|
||||
allocParams.bytesize = hostArrays->bytes;
|
||||
allocParams.poolProps.allocType = cudaMemAllocationTypePinned;
|
||||
allocParams.poolProps.location.id = device;
|
||||
allocParams.poolProps.location.type = cudaMemLocationTypeDevice;
|
||||
|
||||
// Kernel launch parameters
|
||||
cudaKernelNodeParams kernelNodeParams = {0};
|
||||
kernelNodeParams.gridDim = dim3(hostArrays->numBlocks, 1, 1);
|
||||
kernelNodeParams.blockDim = dim3(THREADS_PER_BLOCK, 1, 1);
|
||||
kernelNodeParams.sharedMemBytes = 0;
|
||||
kernelNodeParams.extra = NULL;
|
||||
|
||||
cudaGraph_t graph;
|
||||
cudaGraphNode_t allocNodeInput, allocNodeSquare, allocNodeNegSquare;
|
||||
cudaGraphNode_t copyNodeInput, copyNodeSquare, copyNodeNegSquare;
|
||||
cudaGraphNode_t squareKernelNode, negateKernelNode;
|
||||
cudaGraphNode_t freeNodeInput, freeNodeSquare;
|
||||
|
||||
// Buffer for storing graph node dependencies
|
||||
std::vector<cudaGraphNode_t> nodeDependencies;
|
||||
|
||||
checkCudaErrors(cudaGraphCreate(&graph, 0));
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemAllocNode(&allocNodeInput, graph, NULL, 0, &allocParams));
|
||||
d_input = (float *)allocParams.dptr;
|
||||
|
||||
// To keep the graph structure simple (fewer branching dependencies),
|
||||
// allocNodeSquare should depend on allocNodeInput
|
||||
checkCudaErrors(cudaGraphAddMemAllocNode(&allocNodeSquare, graph, &allocNodeInput, 1, &allocParams));
|
||||
d_square = (float *)allocParams.dptr;
|
||||
|
||||
// copyNodeInput needs to depend on allocNodeInput because copyNodeInput
|
||||
// writes to d_input. It does so here indirectly through allocNodeSquare.
|
||||
checkCudaErrors(cudaGraphAddMemcpyNode1D(©NodeInput,
|
||||
graph,
|
||||
&allocNodeSquare,
|
||||
1,
|
||||
d_input,
|
||||
hostArrays->input,
|
||||
hostArrays->bytes,
|
||||
cudaMemcpyHostToDevice));
|
||||
|
||||
void *squareKernelArgs[3] = {(void *)&d_input, (void *)&d_square, (void *)&(hostArrays->numElements)};
|
||||
kernelNodeParams.func = (void *)squareArray;
|
||||
kernelNodeParams.kernelParams = (void **)squareKernelArgs;
|
||||
|
||||
// Square kernel depends on copyNodeInput to ensure all data is on the device
|
||||
// before kernel launch.
|
||||
checkCudaErrors(cudaGraphAddKernelNode(&squareKernelNode, graph, ©NodeInput, 1, &kernelNodeParams));
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemcpyNode1D(©NodeSquare,
|
||||
graph,
|
||||
&squareKernelNode,
|
||||
1,
|
||||
hostArrays->square,
|
||||
d_square,
|
||||
hostArrays->bytes,
|
||||
cudaMemcpyDeviceToHost));
|
||||
|
||||
// Free of d_input depends on the square kernel to ensure that d_input is not
|
||||
// freed while being read by the kernel. It also depends on the alloc of
|
||||
// d_input via squareKernelNode > copyNodeInput > allocNodeSquare >
|
||||
// allocNodeInput.
|
||||
checkCudaErrors(cudaGraphAddMemFreeNode(&freeNodeInput, graph, &squareKernelNode, 1, d_input));
|
||||
|
||||
// Allocation of C depends on free of A so CUDA can reuse the virtual address.
|
||||
checkCudaErrors(cudaGraphAddMemAllocNode(&allocNodeNegSquare, graph, &freeNodeInput, 1, &allocParams));
|
||||
d_negSquare = (float *)allocParams.dptr;
|
||||
|
||||
if (d_negSquare == d_input) {
|
||||
printf("Check verified that d_negSquare and d_input share a virtual "
|
||||
"address.\n");
|
||||
}
|
||||
|
||||
void *negateKernelArgs[3] = {(void *)&d_square, (void *)&d_negSquare, (void *)&(hostArrays->numElements)};
|
||||
kernelNodeParams.func = (void *)negateArray;
|
||||
kernelNodeParams.kernelParams = (void **)negateKernelArgs;
|
||||
|
||||
checkCudaErrors(cudaGraphAddKernelNode(&negateKernelNode, graph, &allocNodeNegSquare, 1, &kernelNodeParams));
|
||||
|
||||
nodeDependencies.push_back(copyNodeSquare);
|
||||
nodeDependencies.push_back(negateKernelNode);
|
||||
checkCudaErrors(
|
||||
cudaGraphAddMemFreeNode(&freeNodeSquare, graph, nodeDependencies.data(), nodeDependencies.size(), d_square));
|
||||
nodeDependencies.clear();
|
||||
|
||||
checkCudaErrors(cudaGraphAddMemcpyNode1D(©NodeNegSquare,
|
||||
graph,
|
||||
&negateKernelNode,
|
||||
1,
|
||||
hostArrays->negSquare,
|
||||
d_negSquare,
|
||||
hostArrays->bytes,
|
||||
cudaMemcpyDeviceToHost));
|
||||
|
||||
if (d_negSquare_out == NULL) {
|
||||
cudaGraphNode_t freeNodeNegSquare;
|
||||
checkCudaErrors(cudaGraphAddMemFreeNode(&freeNodeNegSquare, graph, ©NodeNegSquare, 1, d_negSquare));
|
||||
}
|
||||
else {
|
||||
*d_negSquare_out = d_negSquare;
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(graphExec, graph, NULL, NULL, 0));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds work to a CUDA stream which negates the square of values in the input
|
||||
* array.
|
||||
*
|
||||
* If d_negSquare_out is non null, then:
|
||||
* 1) d_negSquare will not be freed;
|
||||
* 2) the value of d_negSquare_out will be set to d_negSquare.
|
||||
*
|
||||
* Diagram of the stream operations in doNegateSquaresInStream
|
||||
* ---------------------------------------------------------------------
|
||||
* | STREAM | STREAM2 |
|
||||
* ---------------------------------------------------------------------
|
||||
*
|
||||
* alloc d_input
|
||||
* |
|
||||
* alloc d_square
|
||||
* |
|
||||
* Memcpy a to device
|
||||
* |
|
||||
* launch kernel squareArray
|
||||
* |
|
||||
* record squareKernelCompleteEvent -->-- wait squareKernelCompleteEvent
|
||||
* | |
|
||||
* free d_input |
|
||||
* | |
|
||||
* allocate d_negSquare Memcpy d_square to host
|
||||
* | |
|
||||
* launch kernel negateArray |
|
||||
* | |
|
||||
* record negateKernelCompleteEvent -->-- wait negateKernelCompleteEvent
|
||||
* | |
|
||||
* Memcpy d_negSquare to host |
|
||||
* | free d_square
|
||||
* free d_negSquare |
|
||||
* | |
|
||||
* wait squareFreeEvent --------------<---- record squareFreeEvent
|
||||
*/
|
||||
void doNegateSquaresInStream(cudaStream_t stream1, negSquareArrays *hostArrays, float **d_negSquare_out = NULL)
|
||||
{
|
||||
float *d_input, *d_square, *d_negSquare;
|
||||
cudaStream_t stream2;
|
||||
cudaEvent_t squareKernelCompleteEvent, negateKernelCompleteEvent, squareFreeEvent;
|
||||
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&stream2, cudaStreamNonBlocking));
|
||||
|
||||
checkCudaErrors(cudaEventCreate(&squareKernelCompleteEvent));
|
||||
checkCudaErrors(cudaEventCreate(&negateKernelCompleteEvent));
|
||||
checkCudaErrors(cudaEventCreate(&squareFreeEvent));
|
||||
|
||||
// Virtual addresses are assigned synchronously when cudaMallocAsync is
|
||||
// called, thus there is no performace benefit gained by separating the
|
||||
// allocations into two streams.
|
||||
checkCudaErrors(cudaMallocAsync(&d_input, hostArrays->bytes, stream1));
|
||||
checkCudaErrors(cudaMallocAsync(&d_square, hostArrays->bytes, stream1));
|
||||
|
||||
checkCudaErrors(cudaMemcpyAsync(d_input, hostArrays->input, hostArrays->bytes, cudaMemcpyHostToDevice, stream1));
|
||||
squareArray<<<hostArrays->numBlocks, THREADS_PER_BLOCK, 0, stream1>>>(d_input, d_square, hostArrays->numElements);
|
||||
checkCudaErrors(cudaEventRecord(squareKernelCompleteEvent, stream1));
|
||||
|
||||
checkCudaErrors(cudaStreamWaitEvent(stream2, squareKernelCompleteEvent, 0));
|
||||
checkCudaErrors(cudaMemcpyAsync(hostArrays->square, d_square, hostArrays->bytes, cudaMemcpyDeviceToHost, stream2));
|
||||
|
||||
checkCudaErrors(cudaFreeAsync(d_input, stream1));
|
||||
checkCudaErrors(cudaMallocAsync(&d_negSquare, hostArrays->bytes, stream1));
|
||||
negateArray<<<hostArrays->numBlocks, THREADS_PER_BLOCK, 0, stream1>>>(
|
||||
d_square, d_negSquare, hostArrays->numElements);
|
||||
checkCudaErrors(cudaEventRecord(negateKernelCompleteEvent, stream1));
|
||||
checkCudaErrors(
|
||||
cudaMemcpyAsync(hostArrays->negSquare, d_negSquare, hostArrays->bytes, cudaMemcpyDeviceToHost, stream1));
|
||||
if (d_negSquare_out == NULL) {
|
||||
checkCudaErrors(cudaFreeAsync(d_negSquare, stream1));
|
||||
}
|
||||
else {
|
||||
*d_negSquare_out = d_negSquare;
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaStreamWaitEvent(stream2, negateKernelCompleteEvent, 0));
|
||||
checkCudaErrors(cudaFreeAsync(d_square, stream2));
|
||||
checkCudaErrors(cudaEventRecord(squareFreeEvent, stream2));
|
||||
|
||||
checkCudaErrors(cudaStreamWaitEvent(stream1, squareFreeEvent, 0));
|
||||
|
||||
checkCudaErrors(cudaStreamDestroy(stream2));
|
||||
checkCudaErrors(cudaEventDestroy(squareKernelCompleteEvent));
|
||||
checkCudaErrors(cudaEventDestroy(negateKernelCompleteEvent));
|
||||
checkCudaErrors(cudaEventDestroy(squareFreeEvent));
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates creating a CUDA graph including memory nodes using stream
|
||||
* capture. createNegateSquaresGraphExplicitly constructs an equivalent graph
|
||||
* without stream capture.
|
||||
*/
|
||||
void createNegateSquaresGraphWithStreamCapture(cudaGraphExec_t *graphExec,
|
||||
negSquareArrays *hostArrays,
|
||||
float **d_negSquare_out = NULL)
|
||||
{
|
||||
cudaGraph_t graph;
|
||||
cudaStream_t stream;
|
||||
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
|
||||
|
||||
checkCudaErrors(cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal));
|
||||
doNegateSquaresInStream(stream, hostArrays, d_negSquare_out);
|
||||
checkCudaErrors(cudaStreamEndCapture(stream, &graph));
|
||||
|
||||
checkCudaErrors(cudaGraphInstantiate(graphExec, graph, NULL, NULL, 0));
|
||||
checkCudaErrors(cudaStreamDestroy(stream));
|
||||
checkCudaErrors(cudaGraphDestroy(graph));
|
||||
}
|
||||
|
||||
void prepareRefArrays(negSquareArrays *hostArrays, negSquareArrays *deviceRefArrays, bool **foundValidationFailure)
|
||||
{
|
||||
deviceRefArrays->bytes = hostArrays->bytes;
|
||||
deviceRefArrays->numElements = hostArrays->numElements;
|
||||
|
||||
for (int i = 0; i < hostArrays->numElements; i++) {
|
||||
hostArrays->square[i] = hostArrays->input[i] * hostArrays->input[i];
|
||||
hostArrays->negSquare[i] = hostArrays->square[i] * -1;
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaMalloc((void **)&deviceRefArrays->negSquare, deviceRefArrays->bytes));
|
||||
checkCudaErrors(
|
||||
cudaMemcpy(deviceRefArrays->negSquare, hostArrays->negSquare, hostArrays->bytes, cudaMemcpyHostToDevice));
|
||||
|
||||
checkCudaErrors(cudaMallocManaged((void **)foundValidationFailure, sizeof(bool)));
|
||||
}
|
||||
|
||||
int checkValidationFailure(bool *foundValidationFailure)
|
||||
{
|
||||
if (*foundValidationFailure) {
|
||||
printf("Validation FAILURE!\n\n");
|
||||
*foundValidationFailure = false;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
else {
|
||||
printf("Validation PASSED!\n\n");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void validateGPU(float *d_negSquare, negSquareArrays devRefArrays, bool *foundValidationFailure)
|
||||
{
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
float ref, diff;
|
||||
|
||||
if (idx < devRefArrays.numElements) {
|
||||
ref = devRefArrays.negSquare[idx];
|
||||
diff = d_negSquare[idx] - ref;
|
||||
diff *= diff;
|
||||
ref *= ref;
|
||||
if (diff / ref > ALLOWABLE_VARIANCE) {
|
||||
*foundValidationFailure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void validateHost(negSquareArrays *hostArrays, bool *foundValidationFailure)
|
||||
{
|
||||
float ref, diff;
|
||||
|
||||
for (int i = 0; i < hostArrays->numElements; i++) {
|
||||
ref = hostArrays->input[i] * hostArrays->input[i] * -1;
|
||||
diff = hostArrays->negSquare[i] - ref;
|
||||
diff *= diff;
|
||||
ref *= ref;
|
||||
if (diff / ref > ALLOWABLE_VARIANCE) {
|
||||
*foundValidationFailure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
negSquareArrays hostArrays, deviceRefArrays;
|
||||
cudaStream_t stream;
|
||||
cudaGraphExec_t graphExec, graphExecFreeC;
|
||||
|
||||
// Declare pointers for GPU buffers
|
||||
float *d_negSquare = NULL;
|
||||
bool *foundValidationFailure = NULL;
|
||||
|
||||
srand(time(0));
|
||||
int device = findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
int driverVersion = 0;
|
||||
int deviceSupportsMemoryPools = 0;
|
||||
|
||||
cudaDriverGetVersion(&driverVersion);
|
||||
printf("Driver version is: %d.%d\n", driverVersion / 1000, (driverVersion % 100) / 10);
|
||||
|
||||
if (driverVersion < 11040) {
|
||||
printf("Waiving execution as driver does not support Graph Memory Nodes\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
cudaDeviceGetAttribute(&deviceSupportsMemoryPools, cudaDevAttrMemoryPoolsSupported, device);
|
||||
if (!deviceSupportsMemoryPools) {
|
||||
printf("Waiving execution as device does not support Memory Pools\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
else {
|
||||
printf("Setting up sample.\n");
|
||||
}
|
||||
|
||||
prepareHostArrays(&hostArrays);
|
||||
prepareRefArrays(&hostArrays, &deviceRefArrays, &foundValidationFailure);
|
||||
checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
|
||||
printf("Setup complete.\n\n");
|
||||
|
||||
printf("Running negateSquares in a stream.\n");
|
||||
doNegateSquaresInStream(stream, &hostArrays);
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
printf("Validating negateSquares in a stream...\n");
|
||||
validateHost(&hostArrays, foundValidationFailure);
|
||||
checkValidationFailure(foundValidationFailure);
|
||||
resetOutputArrays(&hostArrays);
|
||||
|
||||
printf("Running negateSquares in a stream-captured graph.\n");
|
||||
createNegateSquaresGraphWithStreamCapture(&graphExec, &hostArrays);
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, stream));
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
printf("Validating negateSquares in a stream-captured graph...\n");
|
||||
validateHost(&hostArrays, foundValidationFailure);
|
||||
checkValidationFailure(foundValidationFailure);
|
||||
resetOutputArrays(&hostArrays);
|
||||
|
||||
printf("Running negateSquares in an explicitly constructed graph.\n");
|
||||
createNegateSquaresGraphExplicitly(&graphExec, device, &hostArrays);
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, stream));
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
printf("Validating negateSquares in an explicitly constructed graph...\n");
|
||||
validateHost(&hostArrays, foundValidationFailure);
|
||||
checkValidationFailure(foundValidationFailure);
|
||||
resetOutputArrays(&hostArrays);
|
||||
|
||||
// Each of the three examples below free d_negSquare outside the graph. As
|
||||
// demonstrated by validateGPU, d_negSquare can be accessed by outside the
|
||||
// graph before d_negSquare is freed.
|
||||
|
||||
printf("Running negateSquares with d_negSquare freed outside the stream.\n");
|
||||
createNegateSquaresGraphExplicitly(&graphExec, device, &hostArrays, &d_negSquare);
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, stream));
|
||||
validateGPU<<<hostArrays.numBlocks, THREADS_PER_BLOCK, 0, stream>>>(
|
||||
d_negSquare, deviceRefArrays, foundValidationFailure);
|
||||
// Since cudaFree is synchronous, the stream must synchronize before freeing
|
||||
// d_negSquare to ensure d_negSquare no longer being accessed.
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
checkCudaErrors(cudaFree(d_negSquare));
|
||||
printf("Validating negateSquares with d_negSquare freed outside the "
|
||||
"stream...\n");
|
||||
validateHost(&hostArrays, foundValidationFailure);
|
||||
checkValidationFailure(foundValidationFailure);
|
||||
resetOutputArrays(&hostArrays);
|
||||
|
||||
printf("Running negateSquares with d_negSquare freed outside the graph.\n");
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, stream));
|
||||
validateGPU<<<hostArrays.numBlocks, THREADS_PER_BLOCK, 0, stream>>>(
|
||||
d_negSquare, deviceRefArrays, foundValidationFailure);
|
||||
checkCudaErrors(cudaFreeAsync(d_negSquare, stream));
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
printf("Validating negateSquares with d_negSquare freed outside the graph...\n");
|
||||
checkValidationFailure(foundValidationFailure);
|
||||
resetOutputArrays(&hostArrays);
|
||||
|
||||
printf("Running negateSquares with d_negSquare freed in a different graph.\n");
|
||||
createFreeGraph(&graphExecFreeC, d_negSquare);
|
||||
checkCudaErrors(cudaGraphLaunch(graphExec, stream));
|
||||
validateGPU<<<hostArrays.numBlocks, THREADS_PER_BLOCK, 0, stream>>>(
|
||||
d_negSquare, deviceRefArrays, foundValidationFailure);
|
||||
checkCudaErrors(cudaGraphLaunch(graphExecFreeC, stream));
|
||||
checkCudaErrors(cudaStreamSynchronize(stream));
|
||||
printf("Validating negateSquares with d_negSquare freed in a different "
|
||||
"graph...\n");
|
||||
checkValidationFailure(foundValidationFailure);
|
||||
|
||||
printf("Cleaning up sample.\n");
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExec));
|
||||
checkCudaErrors(cudaGraphExecDestroy(graphExecFreeC));
|
||||
checkCudaErrors(cudaStreamDestroy(stream));
|
||||
checkCudaErrors(cudaFree(foundValidationFailure));
|
||||
checkCudaErrors(cudaFree(deviceRefArrays.negSquare));
|
||||
free(hostArrays.input);
|
||||
free(hostArrays.square);
|
||||
free(hostArrays.negSquare);
|
||||
printf("Cleanup complete. Exiting sample.\n");
|
||||
}
|
||||
18
cpp/3_CUDA_Features/immaTensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
18
cpp/3_CUDA_Features/immaTensorCoreGemm/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
cpp/3_CUDA_Features/immaTensorCoreGemm/.vscode/extensions.json
vendored
Normal file
7
cpp/3_CUDA_Features/immaTensorCoreGemm/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
35
cpp/3_CUDA_Features/immaTensorCoreGemm/CMakeLists.txt
Normal file
35
cpp/3_CUDA_Features/immaTensorCoreGemm/CMakeLists.txt
Normal file
@@ -0,0 +1,35 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
|
||||
|
||||
project(immaTensorCoreGemm LANGUAGES C CXX CUDA)
|
||||
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
|
||||
|
||||
if(ENABLE_CUDA_DEBUG)
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
|
||||
else()
|
||||
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
|
||||
endif()
|
||||
|
||||
# Include directories and libraries
|
||||
include_directories(../../../Common)
|
||||
|
||||
# Source file
|
||||
# Add target for immaTensorCoreGemm
|
||||
add_executable(immaTensorCoreGemm immaTensorCoreGemm.cu)
|
||||
|
||||
target_compile_options(immaTensorCoreGemm PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
|
||||
|
||||
target_compile_features(immaTensorCoreGemm PRIVATE cxx_std_17 cuda_std_17)
|
||||
|
||||
set_target_properties(immaTensorCoreGemm PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
|
||||
|
||||
# Include installation configuration
|
||||
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
|
||||
setup_samples_install()
|
||||
32
cpp/3_CUDA_Features/immaTensorCoreGemm/README.md
Normal file
32
cpp/3_CUDA_Features/immaTensorCoreGemm/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# immaTensorCoreGemm - Tensor Core GEMM Integer MMA
|
||||
|
||||
## Description
|
||||
|
||||
CUDA sample demonstrating a integer GEMM computation using the Warp Matrix Multiply and Accumulate (WMMA) API for integer introduced in CUDA 10. This sample demonstrates the use of the CUDA WMMA API employing the Tensor Cores introduced in the Volta chip family for faster matrix operations. In addition to that, it demonstrates the use of the new CUDA function attribute cudaFuncAttributeMaxDynamicSharedMemorySize that allows the application to reserve an extended amount of shared memory than it is available by default.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Matrix Multiply, WMMA, Tensor Cores
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, aarch64
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaMemcpy, cudaFree, cudaGetErrorString, cudaGetLastError, cudaEventSynchronize, cudaFuncSetAttribute, cudaEventRecord, cudaMemset, cudaMalloc, cudaEventElapsedTime, cudaGetDeviceProperties, cudaEventCreate
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
|
||||
## References (for more details)
|
||||
632
cpp/3_CUDA_Features/immaTensorCoreGemm/immaTensorCoreGemm.cu
Normal file
632
cpp/3_CUDA_Features/immaTensorCoreGemm/immaTensorCoreGemm.cu
Normal file
@@ -0,0 +1,632 @@
|
||||
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// CUDA sample demonstrating a integer GEMM computation using the Warp Matrix
|
||||
// Multiply and Accumulate API.
|
||||
|
||||
// In this program, the compute_gemm kernel computes the result of a matrix
|
||||
// multiplication and addition: D = alpha * A * B + beta * C. The dimensions of
|
||||
// both C and D matrices are M_GLOBAL x N_GLOBAL. The A matrix is M_GLOBAL x
|
||||
// K_GLOBAL (row-major), the B matrix is K_GLOBAL x N_GLOBAL (column-major). In
|
||||
// that kernel, each CTA computes one 128 x 128 tile of the resulting matrix per
|
||||
// iteration. When the tile is computed, the CTA stores it to the global memory
|
||||
// and begins a new iteration, selecting a new 128 x 128 tile to compute.
|
||||
// Each CTA consists of eight warps. For the 128 x 128 tile, each warp computes
|
||||
// eight 16 x 16 subtiles, organized in a 2 x 4 two-dimensional array. Warps
|
||||
// compute the 16 x 16 subtiles using nvcuda::wmma::mma_sync operations by
|
||||
// moving through the K_GLOBAL dimension of the A and B matrices and
|
||||
// accumulating the intermediate result in the local thread state.
|
||||
|
||||
// There are a number of simple optimizations used in the algorithm:
|
||||
// - The CTA copies the 128 x 128 tile of the C matrix from the global memory to
|
||||
// shared memory. After that is done, each warp loads the C matrix fragments
|
||||
// from shared memory, thus avoiding a random global memory access.
|
||||
// - On each internal iteration, the CTA copies a portion of the A and B
|
||||
// matrices from
|
||||
// global memory to shared memory. After that, all warps in the CTA reuse the
|
||||
// A and B data from shared memory, thus reducing the number of data copies
|
||||
// from global memory.
|
||||
// - The portions of the A and B matrices are stored in shared memory with an
|
||||
// additional
|
||||
// padding (skew) to reduce the number of shared memory access bank conflicts.
|
||||
// (See a detailed explanation near the SKEW_HALF macro definition.)
|
||||
// - When the CTA finishes computing the tiles of the resulting matrix, each
|
||||
// warp stores
|
||||
// its subtiles to shared memory. The CTA then copies the shared memory
|
||||
// contents to global memory, again avoiding redundant random global memory
|
||||
// accesses.
|
||||
// - Note that the CTA tile size is chosen to maximize the GPU register
|
||||
// utilization,
|
||||
// but carefully enough to avoid local memory use.
|
||||
|
||||
#include <assert.h>
|
||||
#include <cuda.h>
|
||||
#include <mma.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// helper functions and utilities to work with CUDA
|
||||
#include <helper_cuda.h>
|
||||
#include <helper_functions.h>
|
||||
|
||||
// Externally configurable parameters.
|
||||
|
||||
#ifndef CPU_DEBUG
|
||||
// Set this to 1 to verify the correctness of the GPU-computed matrix.
|
||||
#define CPU_DEBUG 0
|
||||
#endif
|
||||
|
||||
#ifndef SHARED_MEMORY_LIMIT_64K
|
||||
// Set this to 0 to use more than 64 Kb of shared memory to cache data, to
|
||||
// improve the performance of the computations on GPU.
|
||||
// Note that you need a GPU that can have more than 64 Kb of shared memory
|
||||
// per multiprocessor.
|
||||
#define SHARED_MEMORY_LIMIT_64K 1
|
||||
#endif
|
||||
|
||||
// GPU configuration.
|
||||
|
||||
#define WARP_SIZE 32
|
||||
|
||||
// MMA matrix tile dimensions.
|
||||
|
||||
#define M 16
|
||||
#define N 16
|
||||
#define K 16
|
||||
|
||||
#define WMMA_M 16
|
||||
#define WMMA_N 16
|
||||
#define WMMA_K 16
|
||||
|
||||
// GEMM configuration.
|
||||
|
||||
#define M_TILES 256
|
||||
#define N_TILES 256
|
||||
#define K_TILES 256
|
||||
|
||||
#define M_GLOBAL (M * M_TILES)
|
||||
#define N_GLOBAL (N * N_TILES)
|
||||
#define K_GLOBAL (K * K_TILES)
|
||||
|
||||
#define C_LAYOUT wmma::mem_row_major
|
||||
|
||||
// Implementation constants.
|
||||
|
||||
#define WARPS_PER_BLOCK 8
|
||||
#define THREADS_PER_BLOCK (WARP_SIZE * WARPS_PER_BLOCK)
|
||||
|
||||
#if SHARED_MEMORY_LIMIT_64K
|
||||
// With only 64 Kb shared memory available, we can fit two 8-tile chunks of
|
||||
// the A and B matrix data, that are 16 * 16 * 8 * 8 * 2 = 32 Kb each
|
||||
// (i.e. two 8x8 arrays of tiles of 16x16 uint8_t-typed elements per CTA).
|
||||
// But we cannot account the 8 Kb total skew overhead, without which the
|
||||
// performance would be severely impacted. So we choose to reduce the chunk size
|
||||
// in half, i.e. the amount of A and B matrix data we cache in shared memory.
|
||||
// Accordingly, this doubles the number of outer iterations across the global K
|
||||
// dimension, which only slightly impacts the performance.
|
||||
#define CHUNK_K 8
|
||||
#else
|
||||
#define CHUNK_K 16
|
||||
#endif
|
||||
|
||||
#define CHUNK_LINE_BYTES (CHUNK_K * K * sizeof(uint8_t))
|
||||
#define WARP_COPY_BYTES (WARP_SIZE * sizeof(int4))
|
||||
#define CHUNK_COPY_LINES_PER_WARP (WARP_COPY_BYTES / CHUNK_LINE_BYTES)
|
||||
#define CHUNK_COPY_LINE_LANES (WARP_SIZE / CHUNK_COPY_LINES_PER_WARP)
|
||||
|
||||
#define BLOCK_ROW_WARPS 2
|
||||
#define BLOCK_COL_WARPS 4
|
||||
|
||||
#define WARP_ROW_TILES 4
|
||||
#define WARP_COL_TILES 2
|
||||
|
||||
#define BLOCK_ROW_TILES (WARP_ROW_TILES * BLOCK_ROW_WARPS)
|
||||
#define BLOCK_COL_TILES (WARP_COL_TILES * BLOCK_COL_WARPS)
|
||||
|
||||
#define GLOBAL_MEM_STRIDE N_GLOBAL
|
||||
|
||||
#define SHMEM_STRIDE (N * BLOCK_ROW_TILES)
|
||||
#define SHMEM_OFFSET (N * WARP_ROW_TILES)
|
||||
|
||||
// The macro below is used to shift rows of the A matrix and columns of the B
|
||||
// matrix in shared memory to minimize possible bank conflicts. Before
|
||||
// performing the nvcuda::wmma::mma_sync operation, the warp must load the
|
||||
// matrix data using the nvcuda::wmma::load_matrix_sync operation. Although the
|
||||
// memory access pattern is not specified for that function, each lane in the
|
||||
// warp can read one or multiple matrix elements from different matrix rows or
|
||||
// columns. For shared memory, such access can result in bank conflicts if
|
||||
// different rows / columns of the matrix map to the same bank. By shifting each
|
||||
// row and column by a few bytes, we make sure that they map to different banks,
|
||||
// thus reducing the number of possible bank conflicts. The number of 32
|
||||
// one-byte "uint8_t" elements is chosen as the minimum possible shift because
|
||||
// we must keep each row and column 256-bit aligned, as required by
|
||||
// nvcuda::wmma::load_matrix_sync.
|
||||
#define SKEW_UINT8 32
|
||||
|
||||
#define checkKernelErrors(expr) \
|
||||
do { \
|
||||
expr; \
|
||||
\
|
||||
cudaError_t __err = cudaGetLastError(); \
|
||||
if (__err != cudaSuccess) { \
|
||||
printf("Line %d: '%s' failed: %s\n", __LINE__, #expr, cudaGetErrorString(__err)); \
|
||||
abort(); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
using namespace nvcuda;
|
||||
|
||||
__host__ void init_host_matrices(uint8_t *a, uint8_t *b, int *c)
|
||||
{
|
||||
for (int i = 0; i < M_GLOBAL; i++) {
|
||||
for (int j = 0; j < K_GLOBAL; j++) {
|
||||
a[i * K_GLOBAL + j] = (uint8_t)(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < N_GLOBAL; i++) {
|
||||
for (int j = 0; j < K_GLOBAL; j++) {
|
||||
b[i * K_GLOBAL + j] = (uint8_t)(rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
for (int t = 0; t < M_GLOBAL * N_GLOBAL; t++) {
|
||||
c[t] = (rand() % 3);
|
||||
}
|
||||
}
|
||||
|
||||
__global__ void compute_gemm_imma(const uint8_t *A, const uint8_t *B, const int *C, int *D, int alpha, int beta)
|
||||
{
|
||||
extern __shared__ uint8_t shmem[][CHUNK_K * K + SKEW_UINT8];
|
||||
|
||||
// Warp and lane identification.
|
||||
const unsigned int warpId = threadIdx.x / WARP_SIZE;
|
||||
const unsigned int laneId = threadIdx.x % WARP_SIZE;
|
||||
|
||||
// Offset in shared memory from which the B matrix is stored.
|
||||
const size_t shmem_idx_b_off = BLOCK_COL_TILES * M;
|
||||
|
||||
// This pointer is used to access the C and D matrix tiles this warp computes.
|
||||
int *shmem_warp_tile_ptr = (int *)&shmem[0][0] + (warpId / 2) * SHMEM_STRIDE * K * 2 + (warpId % 2) * SHMEM_OFFSET;
|
||||
|
||||
// This pointer is used to stream the C and D matrices block-wide tile to and
|
||||
// from shared memory.
|
||||
int *shmem_warp_stream_ptr = (int *)&shmem[0][0] + warpId * SHMEM_STRIDE * K;
|
||||
|
||||
// Adjust the beta scaler, as it'll be multiplied by alpha at the end of
|
||||
// each tile computation. Technically this is not generally correct (may
|
||||
// result in a loss of precision). Zero still needs to be specially handled
|
||||
// though.
|
||||
beta /= alpha;
|
||||
|
||||
// Each CTA slides along the 128 x 128 tiles from the top left corner of the
|
||||
// matrix to the right and down, and selects the next tile to compute. Once
|
||||
// there's no such tile, all warps in this CTA exit.
|
||||
for (unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) {
|
||||
const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES);
|
||||
const unsigned int block_tile_j = (block_pos * BLOCK_COL_TILES) % N_TILES;
|
||||
|
||||
// Stop when there are no more D matrix tiles to compute in this CTA.
|
||||
if (block_tile_i >= M_TILES) {
|
||||
break;
|
||||
}
|
||||
|
||||
// This warp's pointer to the C matrix data to copy memory from to shared
|
||||
// memory.
|
||||
const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N;
|
||||
const int *src_gmem_warp_stream_ptr = &C[gmem_idx];
|
||||
|
||||
// Stream multiple C tiles to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < K; i++) {
|
||||
typedef int4 copy_t;
|
||||
|
||||
*((copy_t *)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId) =
|
||||
*((copy_t *)(src_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// These fragments will accumulate the result of A and B matrix fragment
|
||||
// multiplications along the K_GLOBAL dimension.
|
||||
wmma::fragment<wmma::accumulator, M, N, K, int> c[WARP_COL_TILES][WARP_ROW_TILES];
|
||||
|
||||
// Load the C matrix tiles into fragments from shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
const int *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N;
|
||||
|
||||
wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Scale the C matrix.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < c[i][j].num_elements; t++) {
|
||||
c[i][j].x[t] *= beta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Select what warp copies what matrix to shared memory.
|
||||
// Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix.
|
||||
const uint8_t *warp_ptr = (warpId < 4) ? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % 4) * 2)
|
||||
: (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % 4) * 2);
|
||||
|
||||
// Go through the global K dimension by a fixed step at a time.
|
||||
#pragma unroll
|
||||
for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) {
|
||||
// Copy slices of the A and B matrices to shared memory.
|
||||
// The first half of the warps in the CTA copy the A matrix, the rest copy
|
||||
// the B matrix.
|
||||
size_t shmem_idx = warpId < (WARPS_PER_BLOCK / 2)
|
||||
? (M * (warpId % (WARPS_PER_BLOCK / 2)) * 2)
|
||||
: (N * (warpId % (WARPS_PER_BLOCK / 2)) * 2 + shmem_idx_b_off);
|
||||
|
||||
// First half of the warp copies the first row / column of the matrix,
|
||||
// the second half of the warp copies the next.
|
||||
int4 *lane_ptr = (int4 *)(warp_ptr + tile_k * K + (laneId / CHUNK_COPY_LINE_LANES) * K_GLOBAL)
|
||||
+ (laneId % CHUNK_COPY_LINE_LANES);
|
||||
|
||||
// Shift the second half of the warp to the next row / column in the
|
||||
// shared memory.
|
||||
shmem_idx += laneId / CHUNK_COPY_LINE_LANES;
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < ((WARP_SIZE / 2) / CHUNK_COPY_LINES_PER_WARP) * 2; i++) {
|
||||
// Copy 16 bytes at once in each lane.
|
||||
*((int4 *)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES)) = *lane_ptr;
|
||||
|
||||
// Advance the global memory pointer and the shared memory index.
|
||||
lane_ptr = (int4 *)((uint8_t *)lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP);
|
||||
shmem_idx += CHUNK_COPY_LINES_PER_WARP;
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Compute a grid of C matrix tiles in each warp.
|
||||
#pragma unroll
|
||||
for (int k_step = 0; k_step < CHUNK_K; k_step++) {
|
||||
wmma::fragment<wmma::matrix_a, M, N, K, uint8_t, wmma::row_major> a[WARP_COL_TILES];
|
||||
wmma::fragment<wmma::matrix_b, M, N, K, uint8_t, wmma::col_major> b[WARP_ROW_TILES];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
size_t shmem_idx_a = (warpId / 2) * M * 2 + (i * M);
|
||||
const uint8_t *tile_ptr = &shmem[shmem_idx_a][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_UINT8);
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
if (i == 0) {
|
||||
// Load the B matrix fragment once, because it is going to be
|
||||
// reused against the other A matrix fragments.
|
||||
size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId % 2) + (j * N);
|
||||
const uint8_t *tile_ptr = &shmem[shmem_idx_b][k_step * K];
|
||||
|
||||
wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_UINT8);
|
||||
}
|
||||
|
||||
wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
// Store the D fragments to shared memory.
|
||||
#pragma unroll
|
||||
for (int i = 0; i < WARP_COL_TILES; i++) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < WARP_ROW_TILES; j++) {
|
||||
#pragma unroll
|
||||
// Uniform, point-wise transformations of ALL fragment elements by ALL
|
||||
// threads in the warp are well-defined even though element indices
|
||||
// within fragment storage are not defined.
|
||||
for (int t = 0; t < c[i][j].num_elements; t++)
|
||||
c[i][j].x[t] *= alpha;
|
||||
|
||||
int *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N;
|
||||
|
||||
wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// Now that shared memory contains all the D tiles, stream them to global
|
||||
// memory.
|
||||
int *dst_gmem_warp_stream_ptr = &D[gmem_idx];
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 0; i < K; i++) {
|
||||
*((int4 *)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) =
|
||||
*((int4 *)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId);
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
|
||||
// Performs an MxNxK GEMM (C=alpha*A*B + beta*C) assuming:
|
||||
// 1) Matrices are packed in memory.
|
||||
// 2) M, N and K are multiples of 16.
|
||||
// 3) Neither A nor B are transposed.
|
||||
// Note: This is a less performant version of the compute_gemm_imma kernel. It
|
||||
// is designed for
|
||||
// demonstration purposes only to show the CUDA WMMA API use without
|
||||
// relying on availability of the shared memory.
|
||||
__global__ void simple_wmma_gemm_imma(const uint8_t *a,
|
||||
const uint8_t *b,
|
||||
const int *c,
|
||||
int *d,
|
||||
int m_ld,
|
||||
int n_ld,
|
||||
int k_ld,
|
||||
int alpha,
|
||||
int beta)
|
||||
{
|
||||
// Leading dimensions. Packed with no transpositions.
|
||||
int lda = m_ld;
|
||||
int ldb = k_ld;
|
||||
int ldc = n_ld;
|
||||
|
||||
// Tile using a 2D grid
|
||||
int warpM = (blockIdx.x * blockDim.x + threadIdx.x) / warpSize;
|
||||
int warpN = (blockIdx.y * blockDim.y + threadIdx.y);
|
||||
|
||||
// Declare the fragments
|
||||
wmma::fragment<wmma::matrix_a, WMMA_M, WMMA_N, WMMA_K, uint8_t, wmma::row_major> a_frag;
|
||||
wmma::fragment<wmma::matrix_b, WMMA_M, WMMA_N, WMMA_K, uint8_t, wmma::col_major> b_frag;
|
||||
wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, int> acc_frag;
|
||||
wmma::fragment<wmma::accumulator, WMMA_M, WMMA_N, WMMA_K, int> c_frag;
|
||||
|
||||
wmma::fill_fragment(acc_frag, 0.0f);
|
||||
|
||||
// Loop over k
|
||||
for (int i = 0; i < k_ld; i += WMMA_K) {
|
||||
int aCol = i;
|
||||
int aRow = warpM * WMMA_M;
|
||||
|
||||
int bCol = i;
|
||||
int bRow = warpN * WMMA_N;
|
||||
|
||||
// Bounds checking
|
||||
if (aRow < m_ld && aCol < k_ld && bRow < k_ld && bCol < n_ld) {
|
||||
// Load the inputs
|
||||
wmma::load_matrix_sync(a_frag, a + aCol + aRow * lda, lda);
|
||||
wmma::load_matrix_sync(b_frag, b + bCol + bRow * ldb, ldb);
|
||||
|
||||
// Perform the matrix multiplication
|
||||
wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag);
|
||||
}
|
||||
}
|
||||
|
||||
// Load in the current value of c, scale it by beta, and add this our result
|
||||
// scaled by alpha
|
||||
int cCol = warpN * WMMA_N;
|
||||
int cRow = warpM * WMMA_M;
|
||||
|
||||
if (cRow < m_ld && cCol < n_ld) {
|
||||
wmma::load_matrix_sync(c_frag, c + cCol + cRow * ldc, ldc, wmma::mem_row_major);
|
||||
|
||||
for (int i = 0; i < c_frag.num_elements; i++) {
|
||||
c_frag.x[i] = alpha * acc_frag.x[i] + beta * c_frag.x[i];
|
||||
}
|
||||
|
||||
// Store the output
|
||||
wmma::store_matrix_sync(d + cCol + cRow * ldc, c_frag, ldc, wmma::mem_row_major);
|
||||
}
|
||||
}
|
||||
|
||||
__host__ void matMultiplyOnHost(uint8_t *A,
|
||||
uint8_t *B,
|
||||
int *C,
|
||||
int alpha,
|
||||
int beta,
|
||||
int numARows,
|
||||
int numAColumns,
|
||||
int numBRows,
|
||||
int numBColumns,
|
||||
int numCRows,
|
||||
int numCColumns)
|
||||
{
|
||||
for (int i = 0; i < numCRows; i++) {
|
||||
for (int j = 0; j < numCColumns; j++) {
|
||||
int temp = 0;
|
||||
|
||||
for (int k = 0; k < numAColumns; k++) {
|
||||
temp += A[i * numAColumns + k] * B[j * numBRows + k];
|
||||
}
|
||||
|
||||
C[i * numCColumns + j] = temp * alpha + beta * C[i * numCColumns + j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
printf("Initializing...\n");
|
||||
|
||||
int dev = findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
cudaDeviceProp deviceProp;
|
||||
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, dev));
|
||||
|
||||
// Tensor cores require a GPU of Volta (SM72) architecture or higher.
|
||||
if (deviceProp.major < 7 || (deviceProp.major <= 7 && deviceProp.minor < 2)) {
|
||||
printf("immaTensorCoreGemm requires SM 7.2 or higher to use Tensor Cores. "
|
||||
"Exiting...\n");
|
||||
exit(EXIT_WAIVED);
|
||||
}
|
||||
|
||||
printf("M: %d (%d x %d)\n", M_GLOBAL, M, M_TILES);
|
||||
printf("N: %d (%d x %d)\n", N_GLOBAL, N, N_TILES);
|
||||
printf("K: %d (%d x %d)\n", K_GLOBAL, K, K_TILES);
|
||||
|
||||
uint8_t *A_h = NULL;
|
||||
uint8_t *B_h = NULL;
|
||||
int *C_h = NULL;
|
||||
#if CPU_DEBUG
|
||||
int *result_hD = NULL;
|
||||
int *result_host = NULL;
|
||||
#endif
|
||||
|
||||
A_h = (uint8_t *)malloc(sizeof(uint8_t) * M_GLOBAL * K_GLOBAL);
|
||||
B_h = (uint8_t *)malloc(sizeof(uint8_t) * K_GLOBAL * N_GLOBAL);
|
||||
C_h = (int *)malloc(sizeof(int) * M_GLOBAL * N_GLOBAL);
|
||||
#if CPU_DEBUG
|
||||
result_hD = (int *)malloc(sizeof(int) * M_GLOBAL * N_GLOBAL);
|
||||
result_host = (int *)malloc(sizeof(int) * M_GLOBAL * N_GLOBAL);
|
||||
#endif
|
||||
|
||||
uint8_t *A = NULL;
|
||||
uint8_t *B = NULL;
|
||||
int *C = NULL;
|
||||
int *D = NULL;
|
||||
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&A), sizeof(uint8_t) * M_GLOBAL * K_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&B), sizeof(uint8_t) * N_GLOBAL * K_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&C), sizeof(int) * M_GLOBAL * N_GLOBAL));
|
||||
checkCudaErrors(cudaMalloc(reinterpret_cast<void **>(&D), sizeof(int) * M_GLOBAL * N_GLOBAL));
|
||||
|
||||
assert(((unsigned long long)A) % 128 == 0);
|
||||
assert(((unsigned long long)B) % 128 == 0);
|
||||
assert(((unsigned long long)C) % 128 == 0);
|
||||
assert(((unsigned long long)D) % 128 == 0);
|
||||
|
||||
init_host_matrices(A_h, B_h, C_h);
|
||||
|
||||
checkCudaErrors(cudaMemcpy(A, A_h, sizeof(uint8_t) * M_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(B, B_h, sizeof(uint8_t) * N_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemcpy(C, C_h, sizeof(int) * M_GLOBAL * N_GLOBAL, cudaMemcpyHostToDevice));
|
||||
checkCudaErrors(cudaMemset(D, 0, sizeof(int) * M_GLOBAL * N_GLOBAL));
|
||||
|
||||
printf("Preparing data for GPU...\n");
|
||||
|
||||
assert(((unsigned long long)A) % 128 == 0);
|
||||
assert(((unsigned long long)B) % 128 == 0);
|
||||
assert(((unsigned long long)C) % 128 == 0);
|
||||
assert(((unsigned long long)D) % 128 == 0);
|
||||
|
||||
enum {
|
||||
// Compute the right amount of shared memory to request.
|
||||
// We need shared memory to hold per-CTA C and D matrix tiles, and to cache
|
||||
// per-CTA chunks
|
||||
// of the A and B matrices. Therefore, the right amount to request is the
|
||||
// maximum of those
|
||||
// two numbers.
|
||||
SHMEM_SZ = MAX(sizeof(uint8_t) * (BLOCK_COL_TILES * M) * (CHUNK_K * K + SKEW_UINT8) * 2,
|
||||
M * (BLOCK_ROW_WARPS * WARP_ROW_TILES) * N * (BLOCK_COL_WARPS * WARP_COL_TILES) * sizeof(int))
|
||||
};
|
||||
|
||||
printf("Required shared memory size: %lu Kb\n", SHMEM_SZ / 1024UL);
|
||||
|
||||
int alpha = 1;
|
||||
int beta = 1;
|
||||
|
||||
cudaEvent_t start, stop;
|
||||
|
||||
checkCudaErrors(cudaEventCreate(&start));
|
||||
checkCudaErrors(cudaEventCreate(&stop));
|
||||
checkCudaErrors(cudaEventRecord(start));
|
||||
|
||||
// If enough shared memory available on the GPU use high performant kernel
|
||||
if (deviceProp.sharedMemPerMultiprocessor >= SHMEM_SZ) {
|
||||
printf("Computing... using high performance kernel compute_gemm_imma \n");
|
||||
|
||||
checkCudaErrors(cudaFuncSetAttribute(compute_gemm_imma, cudaFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ));
|
||||
checkKernelErrors((compute_gemm_imma<<<deviceProp.multiProcessorCount, THREADS_PER_BLOCK, SHMEM_SZ>>>(
|
||||
A, B, C, D, alpha, beta)));
|
||||
#if CPU_DEBUG
|
||||
checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(int) * M_GLOBAL * N_GLOBAL, cudaMemcpyDeviceToHost));
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
dim3 gridDim;
|
||||
dim3 blockDim;
|
||||
|
||||
// blockDim.x must be a multiple of warpSize
|
||||
// 128x4 means we have 16 warps and a block computes a 64x64 output tile
|
||||
blockDim.x = 128;
|
||||
blockDim.y = 4;
|
||||
|
||||
gridDim.x = (M_GLOBAL + (WMMA_M * blockDim.x / 32 - 1)) / (WMMA_M * blockDim.x / 32);
|
||||
gridDim.y = (N_GLOBAL + WMMA_N * blockDim.y - 1) / (WMMA_N * blockDim.y);
|
||||
|
||||
printf("Computing... using simple_wmma_gemm_imma kernel\n");
|
||||
simple_wmma_gemm_imma<<<gridDim, blockDim>>>(A, B, C, D, M_GLOBAL, N_GLOBAL, K_GLOBAL, alpha, beta);
|
||||
#if CPU_DEBUG
|
||||
checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(int) * M_GLOBAL * N_GLOBAL, cudaMemcpyDeviceToHost));
|
||||
#endif
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaEventRecord(stop));
|
||||
checkCudaErrors(cudaEventSynchronize(stop));
|
||||
|
||||
#if CPU_DEBUG
|
||||
printf("Verifying correctness of the computations...\n");
|
||||
|
||||
memcpy(result_host, C_h, sizeof(int) * M_GLOBAL * N_GLOBAL);
|
||||
|
||||
matMultiplyOnHost(A_h, B_h, result_host, alpha, beta, M_GLOBAL, K_GLOBAL, K_GLOBAL, N_GLOBAL, M_GLOBAL, N_GLOBAL);
|
||||
|
||||
for (int i = 0; i < N_GLOBAL * M_GLOBAL; i++) {
|
||||
if (abs(result_hD[i] - result_host[i]) > 0) {
|
||||
printf("mismatch i=%d result_hD=%d result_host=%d\n", i, result_hD[i], result_host[i]);
|
||||
}
|
||||
}
|
||||
free(result_host);
|
||||
free(result_hD);
|
||||
#endif
|
||||
|
||||
float milliseconds = 0;
|
||||
|
||||
checkCudaErrors(cudaEventElapsedTime(&milliseconds, start, stop));
|
||||
|
||||
printf("Time: %f ms\n", milliseconds);
|
||||
printf("TOPS: %.2f\n", (((double)M_GLOBAL * N_GLOBAL * K_GLOBAL * 2) / (milliseconds / 1000.)) / 1e12);
|
||||
|
||||
free(A_h);
|
||||
free(B_h);
|
||||
free(C_h);
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(A)));
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(B)));
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(C)));
|
||||
checkCudaErrors(cudaFree(reinterpret_cast<void *>(D)));
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user