diff --git a/.azure-pipelines/cuda-unit-test.yml b/.azure-pipelines/cuda-unit-test.yml index be06491e8..2e0d23e34 100644 --- a/.azure-pipelines/cuda-unit-test.yml +++ b/.azure-pipelines/cuda-unit-test.yml @@ -36,6 +36,13 @@ steps: - script: | SB_MICRO_PATH=$PWD make cppbuild displayName: Build benchmarks + - script: | + set -e + cd superbench/benchmarks/micro_benchmarks/cudnn_function/build + cmake --build . --target cudnn_config_test + ctest -R '^cudnn_config$' --output-on-failure --no-tests=error + ctest -R '^cudnn_algorithm_calls$' --output-on-failure --no-tests=error + displayName: Test cuDNN algorithm selection and execution - script: | SB_MICRO_PATH=$PWD python3 setup.py test displayName: Run unit tests diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt index 00ab0e470..cbb915cf7 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt @@ -4,6 +4,8 @@ cmake_minimum_required(VERSION 3.18) project(cudnn_benchmark LANGUAGES CXX) +include(CTest) + find_package(CUDAToolkit QUIET) if(CUDAToolkit_FOUND) include(../cuda_common.cmake) @@ -30,5 +32,17 @@ if(CUDAToolkit_FOUND) add_executable(cudnn_benchmark cudnn_test.cpp) target_link_libraries(cudnn_benchmark ${TARGET_NAME} nlohmann_json::nlohmann_json CUDA::cudart ${CUDNN_LIBRARY}) + + set(CUDNN_CONFIG_TEST_SOURCE + ${CMAKE_CURRENT_SOURCE_DIR}/../../../../tests/benchmarks/micro_benchmarks/test_cudnn_execution_config.cpp) + if(BUILD_TESTING AND EXISTS "${CUDNN_CONFIG_TEST_SOURCE}") + add_executable(cudnn_config_test EXCLUDE_FROM_ALL ${CUDNN_CONFIG_TEST_SOURCE}) + target_include_directories(cudnn_config_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_compile_features(cudnn_config_test PRIVATE cxx_std_14) + target_link_libraries(cudnn_config_test PRIVATE ${TARGET_NAME} CUDA::cudart ${CUDNN_LIBRARY}) + add_test(NAME cudnn_config COMMAND cudnn_config_test) + add_test(NAME cudnn_algorithm_calls COMMAND cudnn_config_test --gpu) + endif() + install(TARGETS cudnn_benchmark ${TARGET_NAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib) endif() diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_data.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_data.h index 1a7c207a8..423ab3555 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_data.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_data.h @@ -12,36 +12,34 @@ namespace cudnn_test { * @tparam T2 conv type */ template class ConvolutionBackwardDataFunction : public CudnnFunction { - cudnnConvolutionBwdDataAlgo_t bwd_data_algo_; + cudnnConvolutionBwdDataAlgo_t selected_algorithm_; /** * @brief Execute the kernel/function */ - virtual void kernel_entry() { + void kernel_entry() override { CHECK_CUDNN_ERROR(cudnnConvolutionBackwardData( this->cudnn_handle, &this->alpha_, this->w_desc_.desc(), this->filter, this->x_desc_.desc(), this->x, - this->conv_desc_.desc(), this->bwd_data_algo_, this->fwd_workspace_, this->fwd_workspace_size_, - &this->beta_, this->h_desc_.desc(), this->h)); + this->conv_desc_.desc(), selected_algorithm_, this->fwd_workspace_, this->fwd_workspace_size_, &this->beta_, + this->h_desc_.desc(), this->h)); } /** - * @brief Get and set convolution algorithm and workspace size used in cudnn convolution functions + * @brief Query workspace bytes for the selected backward-data algorithm */ - virtual void get_workspace_size() { - bwd_data_algo_ = cudnnConvolutionBwdDataAlgo_t(this->algo_); + size_t get_workspace_size() const override { + size_t bytes; CHECK_CUDNN_ERROR(cudnnGetConvolutionBackwardDataWorkspaceSize( this->cudnn_handle, this->w_desc_.desc(), this->x_desc_.desc(), this->conv_desc_.desc(), - this->h_desc_.desc(), this->bwd_data_algo_, &this->fwd_workspace_size_)); + this->h_desc_.desc(), selected_algorithm_, &bytes)); + return bytes; } /** - * @brief Find the best algorithm for cudnn convolution functions + * @brief Resolve the backward-data algorithm before querying workspace or running the convolution */ - virtual void find_best_algo() { - int algo_count; - cudnnConvolutionBwdDataAlgoPerf_t perf_results; - CHECK_CUDNN_ERROR(cudnnFindConvolutionBackwardDataAlgorithm( - this->cudnn_handle, this->w_desc_.desc(), this->x_desc_.desc(), this->conv_desc_.desc(), - this->h_desc_.desc(), 1, &algo_count, &perf_results)); - this->algo_ = perf_results.algo; + void select_algorithm() override { + selected_algorithm_ = select_convolution_algorithm( + *this, cudnnFindConvolutionBackwardDataAlgorithm, this->cudnn_handle, this->w_desc_.desc(), + this->x_desc_.desc(), this->conv_desc_.desc(), this->h_desc_.desc()); } public: diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_filter.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_filter.h index 6873ea4c9..46af36278 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_filter.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_backward_filter.h @@ -12,35 +12,33 @@ namespace cudnn_test { * @tparam T2 conv type */ template class ConvolutionBackwardFilterFunction : public CudnnFunction { - cudnnConvolutionBwdFilterAlgo_t bwd_filter_algo_; + cudnnConvolutionBwdFilterAlgo_t selected_algorithm_; /** * @brief Execute the kernel/function */ - virtual void kernel_entry() { + void kernel_entry() override { CHECK_CUDNN_ERROR(cudnnConvolutionBackwardFilter( this->cudnn_handle, &this->alpha_, this->x_desc_.desc(), this->x, this->h_desc_.desc(), this->h, - this->conv_desc_.desc(), this->bwd_filter_algo_, this->fwd_workspace_, this->fwd_workspace_size_, - &this->beta_, this->w_desc_.desc(), this->filter)); + this->conv_desc_.desc(), selected_algorithm_, this->fwd_workspace_, this->fwd_workspace_size_, &this->beta_, + this->w_desc_.desc(), this->filter)); } /** - * @brief Get and set convolution algorithm and workspace size used in cudnn convolution functions + * @brief Query workspace bytes for the selected backward-filter algorithm */ - virtual void get_workspace_size() { - bwd_filter_algo_ = cudnnConvolutionBwdFilterAlgo_t(this->algo_); + size_t get_workspace_size() const override { + size_t bytes; CHECK_CUDNN_ERROR(cudnnGetConvolutionBackwardFilterWorkspaceSize( this->cudnn_handle, this->x_desc_.desc(), this->h_desc_.desc(), this->conv_desc_.desc(), - this->w_desc_.desc(), this->bwd_filter_algo_, &this->fwd_workspace_size_)); + this->w_desc_.desc(), selected_algorithm_, &bytes)); + return bytes; } /** - * @brief Find the best algorithm for cudnn convolution functions + * @brief Resolve the backward-filter algorithm before querying workspace or running the convolution */ - virtual void find_best_algo() { - int algo_count; - cudnnConvolutionBwdFilterAlgoPerf_t perf_results; - CHECK_CUDNN_ERROR(cudnnFindConvolutionBackwardFilterAlgorithm( - this->cudnn_handle, this->x_desc_.desc(), this->h_desc_.desc(), this->conv_desc_.desc(), - this->w_desc_.desc(), 1, &algo_count, &perf_results)); - this->algo_ = perf_results.algo; + void select_algorithm() override { + selected_algorithm_ = select_convolution_algorithm( + *this, cudnnFindConvolutionBackwardFilterAlgorithm, this->cudnn_handle, this->x_desc_.desc(), + this->h_desc_.desc(), this->conv_desc_.desc(), this->w_desc_.desc()); } public: diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_forward.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_forward.h index 7b1f1764b..5df28bd19 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_forward.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/convolution_forward.h @@ -12,35 +12,33 @@ namespace cudnn_test { * @tparam T2 conv type */ template class ConvolutionForwardFunction : public CudnnFunction { - cudnnConvolutionFwdAlgo_t fwd_algo_; + cudnnConvolutionFwdAlgo_t selected_algorithm_; /** * @brief Execute the kernel/function */ - virtual void kernel_entry() { + void kernel_entry() override { CHECK_CUDNN_ERROR(cudnnConvolutionForward(this->cudnn_handle, &this->alpha_, this->x_desc_.desc(), this->x, this->w_desc_.desc(), this->filter, this->conv_desc_.desc(), - this->fwd_algo_, this->fwd_workspace_, this->fwd_workspace_size_, + selected_algorithm_, this->fwd_workspace_, this->fwd_workspace_size_, &this->beta_, this->h_desc_.desc(), this->h)); } /** - * @brief Get and set convolution algorithm and workspace size used in cudnn convolution functions + * @brief Query workspace bytes for the selected forward algorithm */ - virtual void get_workspace_size() { - fwd_algo_ = cudnnConvolutionFwdAlgo_t(this->algo_); - CHECK_CUDNN_ERROR(cudnnGetConvolutionForwardWorkspaceSize( - this->cudnn_handle, this->x_desc_.desc(), this->w_desc_.desc(), this->conv_desc_.desc(), - this->h_desc_.desc(), this->fwd_algo_, &this->fwd_workspace_size_)); + size_t get_workspace_size() const override { + size_t bytes; + CHECK_CUDNN_ERROR(cudnnGetConvolutionForwardWorkspaceSize(this->cudnn_handle, this->x_desc_.desc(), + this->w_desc_.desc(), this->conv_desc_.desc(), + this->h_desc_.desc(), selected_algorithm_, &bytes)); + return bytes; } /** - * @brief Find the best algorithm for cudnn convolution functions + * @brief Resolve the forward algorithm before querying workspace or running the convolution */ - virtual void find_best_algo() { - int algo_count; - cudnnConvolutionFwdAlgoPerf_t perf_results; - CHECK_CUDNN_ERROR(cudnnFindConvolutionForwardAlgorithm(this->cudnn_handle, this->x_desc_.desc(), - this->w_desc_.desc(), this->conv_desc_.desc(), - this->h_desc_.desc(), 1, &algo_count, &perf_results)); - this->algo_ = perf_results.algo; + void select_algorithm() override { + selected_algorithm_ = select_convolution_algorithm( + *this, cudnnFindConvolutionForwardAlgorithm, this->cudnn_handle, this->x_desc_.desc(), this->w_desc_.desc(), + this->conv_desc_.desc(), this->h_desc_.desc()); } public: diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h index f23649f4a..e28fb3f2f 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h @@ -5,11 +5,26 @@ #include #include +#include #include #include "cudnn_config.h" namespace cudnn_test { +template +auto select_convolution_algorithm(CudnnConfig &config, Find find, Args... args) -> decltype(Perf::algo) { + if (!config.get_auto_algo()) + return static_cast(config.get_algo()); + + int count = 0; + Perf candidate; + CHECK_CUDNN_ERROR(find(args..., 1, &count, &candidate)); + if (count != 1) + throw std::runtime_error(config.get_name() + ": expected one cuDNN algorithm, got " + std::to_string(count)); + CHECK_CUDNN_ERROR(candidate.status); + return candidate.algo; +} + /** * @brief Generation of cudnn functions' params and run the benchmark of this function * @@ -25,7 +40,7 @@ template class CudnnFunction : public CudnnConfig { TensorDescriptorNd h_desc_; size_t fwd_workspace_size_; float *fwd_workspace_; - T1 *x, *filter, *h; + T1 *x = nullptr, *filter = nullptr, *h = nullptr; const float alpha_ = 1.f; const float beta_ = 0.f; @@ -34,21 +49,22 @@ template class CudnnFunction : public CudnnConfig { */ void prepare_input(); /** - * @brief Generate some params used in the cudnn function + * @brief Create descriptors from the convolution workload */ - void prepare_for_function(); + void prepare_descriptors(); /** - * @brief Get and set convolution algorithm and workspace size used in cudnn convolution functions + * @brief Apply the existing math/algorithm policy and allocate workspace */ - virtual void get_workspace_size() {} + void prepare_execution(); /** - * @brief launch the kernel/function + * @brief Select the operation-specific algorithm used by both the workspace query and the convolution */ - virtual void kernel_entry() {} + virtual void select_algorithm() = 0; + virtual size_t get_workspace_size() const = 0; /** - * @brief Find the best algorithm for cudnn convolution functions + * @brief launch the kernel/function */ - virtual void find_best_algo() {} + virtual void kernel_entry() = 0; public: /** @@ -78,24 +94,24 @@ template class CudnnFunction : public CudnnConfig { }; /** - * @brief Generate some params used in the cudnn function + * @brief Create descriptors from the convolution workload */ -template void CudnnFunction::prepare_for_function() { - // Generate descriptor +template void CudnnFunction::prepare_descriptors() { conv_desc_ = ConvolutionDescriptor(get_array_length(), get_padA(), get_filter_strideA(), get_dilationA(), get_mode()); x_desc_ = TensorDescriptorNd(get_input_dims(), get_input_stride()); w_desc_ = FilterDescriptorNd(get_filter_dims()); h_desc_ = TensorDescriptorNd(get_output_dims(), get_output_stride()); +} - // Set Convolution MathType - cudnnMathType_t algo = get_use_tensor_op() ? CUDNN_TENSOR_OP_MATH : CUDNN_DEFAULT_MATH; - CHECK_CUDNN_ERROR(cudnnSetConvolutionMathType(conv_desc_.desc(), algo)); - if (this->auto_algo_) { - find_best_algo(); - } - // Set convolution algorithm and workspace size - this->get_workspace_size(); +/** + * @brief Apply the existing math/algorithm policy and allocate workspace + */ +template void CudnnFunction::prepare_execution() { + const auto math_type = get_use_tensor_op() ? CUDNN_TENSOR_OP_MATH : CUDNN_DEFAULT_MATH; + CHECK_CUDNN_ERROR(cudnnSetConvolutionMathType(conv_desc_.desc(), math_type)); + select_algorithm(); + fwd_workspace_size_ = get_workspace_size(); zeros(&fwd_workspace_, std::vector{static_cast(this->fwd_workspace_size_ / sizeof(float)), 1}); } /** @@ -113,9 +129,8 @@ template void CudnnFunction::prepare_input() * @brief The main procedure for cudnn function test, including warmup, function test and time measurement */ template void CudnnFunction::benchmark() { - // Prepare some Prerequisites for function running - prepare_for_function(); - // Allocate memory and fill with data of input and output tensor + prepare_descriptors(); + prepare_execution(); prepare_input(); // Warm up diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h index 7047adbb4..26c559ce7 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h @@ -7,8 +7,10 @@ #pragma once +#include #include #include +#include #include #include #include @@ -145,7 +147,7 @@ template class FilterDescriptorNd { CHECK_CUDNN_ERROR(cudnnSetFilterNdDescriptor(*desc_, type, tensor_format, dim.size(), &dim[0])); } - cudnnFilterDescriptor_t desc() { return *desc_; } + cudnnFilterDescriptor_t desc() const { return *desc_; } }; /** diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_execution_config.cpp b/tests/benchmarks/micro_benchmarks/test_cudnn_execution_config.cpp new file mode 100644 index 000000000..21e9c262e --- /dev/null +++ b/tests/benchmarks/micro_benchmarks/test_cudnn_execution_config.cpp @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#include "cudnn_function.h" + +namespace { +int expected, searches, queries, executions; + +template auto trace_find(Find find) { + return [find](auto handle, auto a, auto b, auto conv, auto out, int requested, int *count, auto *result) { + ++searches; + auto status = find(handle, a, b, conv, out, requested, count, result); + if (status == CUDNN_STATUS_SUCCESS && *count == 1 && result->status == CUDNN_STATUS_SUCCESS) + expected = result->algo; + return status; + }; +} + +template cudnnStatus_t trace(int &calls, Fn fn, Args... args) { + if (std::get(std::tie(args...)) != expected) + throw std::runtime_error("cuDNN call did not receive the selected algorithm"); + ++calls; + return fn(args...); +} +} // namespace + +// Observe the actual cuDNN calls in this test translation unit; forward all arguments to the real library. +#define cudnnFindConvolutionForwardAlgorithm trace_find(cudnnFindConvolutionForwardAlgorithm) +#define cudnnFindConvolutionBackwardDataAlgorithm trace_find(cudnnFindConvolutionBackwardDataAlgorithm) +#define cudnnFindConvolutionBackwardFilterAlgorithm trace_find(cudnnFindConvolutionBackwardFilterAlgorithm) +#define cudnnGetConvolutionForwardWorkspaceSize(...) \ + trace<5>(queries, cudnnGetConvolutionForwardWorkspaceSize, __VA_ARGS__) +#define cudnnGetConvolutionBackwardDataWorkspaceSize(...) \ + trace<5>(queries, cudnnGetConvolutionBackwardDataWorkspaceSize, __VA_ARGS__) +#define cudnnGetConvolutionBackwardFilterWorkspaceSize(...) \ + trace<5>(queries, cudnnGetConvolutionBackwardFilterWorkspaceSize, __VA_ARGS__) +#define cudnnConvolutionForward(...) trace<7>(executions, cudnnConvolutionForward, __VA_ARGS__) +#define cudnnConvolutionBackwardData(...) trace<7>(executions, cudnnConvolutionBackwardData, __VA_ARGS__) +#define cudnnConvolutionBackwardFilter(...) trace<7>(executions, cudnnConvolutionBackwardFilter, __VA_ARGS__) +#include "convolution_backward_data.h" +#include "convolution_backward_filter.h" +#include "convolution_forward.h" + +using namespace cudnn_test; + +static void check_search_errors(CudnnConfig &config) { + config.set_auto_algo(true); + for (int count : {0, 1}) { + auto find = [count](int, int *n, cudnnConvolutionFwdAlgoPerf_t *result) { + *n = count; + result->status = count ? CUDNN_STATUS_ALLOC_FAILED : CUDNN_STATUS_SUCCESS; + result->algo = CUDNN_CONVOLUTION_FWD_ALGO_GEMM; + return CUDNN_STATUS_SUCCESS; + }; + try { + select_convolution_algorithm(config, find); + } catch (const std::runtime_error &e) { + if (std::string(e.what()).find(count ? cudnnGetErrorString(CUDNN_STATUS_ALLOC_FAILED) : "got 0") != + std::string::npos) + continue; + throw; + } + throw std::runtime_error("accepted an empty or failed cuDNN search result"); + } +} + +template void check_calls(CudnnConfig &config) { + for (bool automatic : {false, true}) { + config.set_auto_algo(automatic); + expected = automatic ? -1 : config.get_algo(); + searches = queries = executions = 0; + Op(config).benchmark(); + if (searches != static_cast(automatic) || queries != 1 || executions != 2) + throw std::runtime_error("unexpected number of cuDNN searches, workspace queries or convolutions"); + } +} + +int main(int argc, char **argv) { + try { + CudnnConfig config{}; + if (argc == 1) { + check_search_errors(config); + return 0; + } + if (argc != 2 || std::string(argv[1]) != "--gpu") + throw std::invalid_argument("usage: cudnn_config_test [--gpu]"); + config.set_input_dims({2, 8, 5, 5}); + config.set_output_dims(config.get_input_dims()); + config.set_input_stride({200, 25, 5, 1}); + config.set_output_stride(config.get_input_stride()); + config.set_filter_dims({8, 8, 3, 3}); + config.set_padA({1, 2}); + config.set_filter_strideA({1, 1}); + config.set_dilationA({1, 2}); + config.set_array_length(2); + config.set_mode(CUDNN_CROSS_CORRELATION); + config.set_algo(1); + config.set_warm_up(1); + config.set_num_test(1); + config.set_num_in_step(1); + check_calls>(config); + check_calls>(config); + check_calls>(config); + } catch (const std::exception &error) { + std::cerr << error.what() << std::endl; + return 1; + } + return 0; +}