From cb4a4972c2c67016dac477737ed67b0ebeb29556 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Tue, 8 Sep 2026 18:35:35 +0000 Subject: [PATCH 1/3] Benchmarks: Fix cuDNN data types and failure handling Keep storage and convolution compute precision independent, seed and transfer half data correctly, and fix workspace, descriptor, and exception safety. Add native, CLI, and parser regressions and document FP16 baseline migration. Preserve the host-wall timing loop, default cases, and metric names. --- .../benchmarks/micro-benchmarks.md | 15 ++ .../micro_benchmarks/cudnn_function.py | 30 +-- .../cudnn_function/CMakeLists.txt | 9 + .../micro_benchmarks/cudnn_function/README.md | 61 +++++ .../cudnn_function/cudnn_config.h | 7 +- .../cudnn_function/cudnn_function.h | 35 ++- .../cudnn_function/cudnn_function_helper.h | 51 ++--- .../cudnn_function/cudnn_helper.cpp | 50 ++++- .../cudnn_function/cudnn_helper.h | 53 ++++- .../micro_benchmarks/test_cudnn_binary.py | 129 +++++++++++ .../test_cudnn_data_types.cpp | 211 ++++++++++++++++++ .../micro_benchmarks/test_cudnn_raw_result.py | 180 +++++++++++++++ 12 files changed, 750 insertions(+), 81 deletions(-) create mode 100644 superbench/benchmarks/micro_benchmarks/cudnn_function/README.md create mode 100644 tests/benchmarks/micro_benchmarks/test_cudnn_binary.py create mode 100644 tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp create mode 100644 tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index d56965a7c..a8ef84b3c 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -110,6 +110,21 @@ The supported functions for cuDNN are as follows: |-----------------------------------------------------------|-----------|------------------------------------------------------------------| | cudnn-function/name\_${function_name}\_${parameters}_time | time (us) | The mean time to execute the cudnn function with the parameters. | +#### Precision and compatibility + +`inputType` selects tensor and filter storage, while `convType` independently selects convolution compute precision. +The cuDNN enum values `0` and `2` represent FP32 and FP16, respectively; supported combinations and algorithms depend on the GPU and cuDNN version. + +Versions with the aliased storage/compute-field defect execute cases requesting `inputType: 2, convType: 0` with FP32 storage instead of FP16 storage. +This affects nine of the eighteen default cuDNN configurations, not other SuperBench benchmarks. +After applying the fix, rebuild the native benchmark and helper library and regenerate baselines for these cases using the repaired source/image. +Do not compare repaired FP16 measurements with the old effective-FP32 baselines just because their metric names match. +Metric names, microsecond units, and the host-wall timing loop are unchanged. + +Native execution failures and missing, malformed, duplicate, or non-finite timing records are not successful measurements. +Keep unsupported configurations visible as failures; do not silently accept them as timing data. +See the [cuDNN regression checks](../../../superbench/benchmarks/micro_benchmarks/cudnn_function/README.md) for focused validation commands. + ### `tensorrt-inference` #### Introduction diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function.py b/superbench/benchmarks/micro_benchmarks/cudnn_function.py index 3bc601742..1a9da676e 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function.py +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function.py @@ -429,18 +429,22 @@ def _process_raw_result(self, cmd_idx, raw_output): metric = metric + '_' + key + '_' + str(cmd_config[key]) metric = metric.replace(' ', '').replace(',', '_') - error = False - raw_data = [] - for line in lines: - if '[raw_data]' in line: - raw_data = line[line.index('[raw_data]: ') + len('[raw_data]: '):] - raw_data = raw_data.split(',') - raw_data.pop() - raw_data = [float(item) for item in raw_data] - self._result.add_result(metric.lower() + '_time', statistics.mean(raw_data) * 1000) - self._result.add_raw_data(metric.lower() + '_time', raw_data, self._args.log_raw_data) - if 'Error' in line: - error = True + if 'Error' in raw_output: + raise ValueError('Error reported in cuDNN output.') + timing_records = [line for line in lines if '[raw_data]' in line] + if len(timing_records) != 1: + raise ValueError('Expected exactly one timing record.') + raw_data = timing_records[0].split('[raw_data]:', 1)[1].strip() + if raw_data.endswith(','): + raw_data = raw_data[:-1] + raw_data = [float(item) for item in raw_data.split(',')] + if len(raw_data) != self._args.num_steps or not all(0 < sample < float('inf') for sample in raw_data): + raise ValueError('Expected exactly {} finite positive timing samples.'.format(self._args.num_steps)) + mean_time = statistics.mean(raw_data) * 1000 + if not 0 < mean_time < float('inf'): + raise ValueError('Expected a finite positive mean time after unit conversion.') + self._result.add_result(metric.lower() + '_time', mean_time) + self._result.add_raw_data(metric.lower() + '_time', raw_data, self._args.log_raw_data) except BaseException as e: logger.error( 'Cannot extract results from cudnn functions - round: {}, index of cmd: {}, \ @@ -448,8 +452,6 @@ def _process_raw_result(self, cmd_idx, raw_output): self._curr_run_index, cmd_idx, self._name, raw_output, str(e) ) ) - error = True - if error: logger.error( 'Error in running cudnn test - round: {}, index of cmd: {}, benchmark: {}, raw data: {}'.format( self._curr_run_index, cmd_idx, self._name, raw_output diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt index 00ab0e470..b04bec2d1 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt @@ -30,5 +30,14 @@ 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_DATA_TYPES_TEST_SOURCE + ${CMAKE_CURRENT_SOURCE_DIR}/../../../../tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp) + if(EXISTS "${CUDNN_DATA_TYPES_TEST_SOURCE}") + add_executable(cudnn_data_types_test EXCLUDE_FROM_ALL ${CUDNN_DATA_TYPES_TEST_SOURCE}) + target_include_directories(cudnn_data_types_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(cudnn_data_types_test ${TARGET_NAME} CUDA::cudart CUDA::cuda_driver ${CUDNN_LIBRARY}) + endif() + install(TARGETS cudnn_benchmark ${TARGET_NAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib) endif() diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/README.md b/superbench/benchmarks/micro_benchmarks/cudnn_function/README.md new file mode 100644 index 000000000..33624e65a --- /dev/null +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/README.md @@ -0,0 +1,61 @@ +# cuDNN Regression Checks + +Run these commands from the repository root in an environment with the supported +CUDA toolkit, cuDNN development libraries, C++ compiler, CMake, and a compatible +NVIDIA GPU. Python parser checks require the normal SuperBench Python dependencies +but do not launch a GPU workload. CMake fetches the existing pinned JSON dependency +unless it is supplied through `FETCHCONTENT_SOURCE_DIR_JSON`. + +## Build And Run + +```bash +cmake -S superbench/benchmarks/micro_benchmarks/cudnn_function \ + -B build/cudnn-tests -DCMAKE_BUILD_TYPE=Release +cmake --build build/cudnn-tests \ + --target cudnn_benchmark cudnn_data_types_test --parallel 2 +CUDA_VISIBLE_DEVICES=0 build/cudnn-tests/cudnn_data_types_test +CUDA_VISIBLE_DEVICES=0 \ + SB_CUDNN_TEST_BINARY="$PWD/build/cudnn-tests/cudnn_benchmark" \ + python3 tests/benchmarks/micro_benchmarks/test_cudnn_binary.py -v +python3 -m unittest discover -s tests/benchmarks/micro_benchmarks \ + -p test_cudnn_raw_result.py -v +``` + +With CUDA 13 installations that place CCCL headers under the toolkit's `include/cccl` +directory, add `-DCMAKE_CXX_FLAGS=-I/usr/local/cuda/include/cccl` when configuring +(adjust the toolkit path). Use the toolkit and architecture flags appropriate to +the target GPU; a build on one architecture is not runtime qualification of another. + +The native test target is excluded from the default build and installation. It is +available when the repository's test source is present, so native-source-only +packages can still configure and build without the tests. The CLI tests skip when +`SB_CUDNN_TEST_BINARY` is unset; set it explicitly for a real native gate. + +## Coverage And Limits + +- Native checks cover independent storage/compute fields, descriptor readback, + seeded half initialization and device transfer, byte-exact workspace requests, + cleanup, unprepared destruction, strided allocation, and invalid descriptor arrays. +- CLI checks exercise all three convolution directions and controlled failures. + FP16 compute and noncontiguous layouts may report `CUDNN_STATUS_NOT_SUPPORTED`; + those paths must exit nonzero without publishing timings. The FP32-storage/FP32- + compute and FP16-storage/FP32-compute contiguous smoke cases must execute. +- Parser checks preserve names, units, raw output, and the failure marker while + rejecting absent, duplicate, malformed, nonpositive, or non-finite measurements. + They also cover the existing executor's aggregate failure and continuation behavior. +- These are execution and integrity checks, not a full numerical-accuracy test, + performance acceptance, or certification of every default algorithm on every stack. + +For a memory check, run: + +```bash +CUDA_VISIBLE_DEVICES=0 compute-sanitizer --tool memcheck --leak-check full \ + --error-exitcode 99 build/cudnn-tests/cudnn_data_types_test --memcheck +``` + +`--memcheck` skips only the deliberate query of a freed workspace address. The +ordinary test retains that negative check, while sanitizer leak detection checks +that allocations are released. Require zero memory errors and zero leaked bytes. + +The repaired FP16-storage/FP32-compute cases need new baselines. See the +[precision and compatibility note](../../../../docs/user-tutorial/benchmarks/micro-benchmarks.md#precision-and-compatibility). diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h index 913ec7fc8..b6ccc1485 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h @@ -3,6 +3,7 @@ #pragma once +#include #include #include "cudnn_helper.h" @@ -79,7 +80,7 @@ class CudnnConfig { void set_mode(const cudnnConvolutionMode_t &mode) { mode_ = mode; } void set_use_tensor_op(bool use_tensor_op) { use_tensor_op_ = use_tensor_op; } void set_input_type(const cudnnDataType_t &input_type) { input_type_ = input_type; } - void set_conv_type(const cudnnDataType_t &conv_type) { input_type_ = conv_type; } + void set_conv_type(const cudnnDataType_t &conv_type) { conv_type_ = conv_type; } void set_function(const std::string &str) { function_str_ = str; } void set_auto_algo(bool auto_algo) { auto_algo_ = auto_algo; } @@ -96,7 +97,7 @@ class CudnnConfig { cudnnConvolutionMode_t &get_mode() { return mode_; } bool get_use_tensor_op() { return use_tensor_op_; } cudnnDataType_t &get_input_type() { return input_type_; } - cudnnDataType_t &get_conv_type() { return input_type_; } + cudnnDataType_t &get_conv_type() { return conv_type_; } std::string &get_name() { return name; } cudnn_function_name_enum get_e_name() { return e_name; } std::string &get_function_str() { return function_str_; } @@ -111,7 +112,7 @@ class CudnnConfig { this->e_name = it->second; return e_name; } else { - throw "ERROR: invalid input function name"; + throw std::invalid_argument("invalid input function name"); } } }; diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h index f23649f4a..cc13c8e89 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h @@ -18,14 +18,16 @@ namespace cudnn_test { */ template class CudnnFunction : public CudnnConfig { protected: - cudnnHandle_t cudnn_handle; + cudnnHandle_t cudnn_handle = nullptr; TensorDescriptorNd x_desc_; FilterDescriptorNd w_desc_; ConvolutionDescriptor conv_desc_; TensorDescriptorNd h_desc_; - size_t fwd_workspace_size_; - float *fwd_workspace_; - T1 *x, *filter, *h; + size_t fwd_workspace_size_ = 0; + float *fwd_workspace_ = nullptr; + T1 *x = nullptr; + T1 *filter = nullptr; + T1 *h = nullptr; const float alpha_ = 1.f; const float beta_ = 0.f; @@ -64,12 +66,18 @@ template class CudnnFunction : public CudnnConfig { /** * @brief Destroy the Cudnn Function object, including free cuda memory and handle of cudnn and curand */ - virtual ~CudnnFunction() { + virtual ~CudnnFunction() noexcept { // free context and memory - CUDA_SAFE_CALL(cudaFree(x)); - CUDA_SAFE_CALL(cudaFree(filter)); - CUDA_SAFE_CALL(cudaFree(h)); - cudnn_handle_free(&this->cudnn_handle); + if (x != nullptr) + cudaFree(x); + if (filter != nullptr) + cudaFree(filter); + if (h != nullptr) + cudaFree(h); + if (fwd_workspace_ != nullptr) + cudaFree(fwd_workspace_); + if (cudnn_handle != nullptr) + cudnnDestroy(cudnn_handle); } /** * @brief The main procedure for cudnn function test, including warmup, function test and time measurement @@ -96,7 +104,10 @@ template void CudnnFunction::prepare_for_func } // Set convolution algorithm and workspace size this->get_workspace_size(); - zeros(&fwd_workspace_, std::vector{static_cast(this->fwd_workspace_size_ / sizeof(float)), 1}); + if (fwd_workspace_size_ > 0) { + CUDA_SAFE_CALL(cudaMalloc(reinterpret_cast(&fwd_workspace_), fwd_workspace_size_)); + CUDA_SAFE_CALL(cudaMemset(fwd_workspace_, 0, fwd_workspace_size_)); + } } /** * @brief Malloc cuda memory and fill in value for data params used in the cudnn function @@ -105,9 +116,9 @@ template void CudnnFunction::prepare_input() // Allocate memory for filter data rand(&filter, get_filter_dims(), random_seed); // Allocate memory for input data - rand(&x, get_input_dims(), random_seed); + rand(&x, tensor_storage_size(get_input_dims(), get_input_stride()), random_seed); // Allocate memory for output data - rand(&h, get_output_dims(), random_seed); + rand(&h, tensor_storage_size(get_output_dims(), get_output_stride()), random_seed); } /** * @brief The main procedure for cudnn function test, including warmup, function test and time measurement diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h index d1f93a8bd..ab9b5b7b9 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -171,7 +172,7 @@ template CudnnFunction *get_cudnn_function_po case e_cudnnConvolutionBackwardFilter: return new ConvolutionBackwardFilterFunction(function); default: - throw "invalid function name"; + throw std::invalid_argument("invalid function name"); } } @@ -185,36 +186,24 @@ template CudnnFunction *get_cudnn_function_po * @param options the cmd arguments of the application */ void run_benchmark(Options &options) { - try { - json function_config = json::parse(options.para_info_json); - // convert function params from json to CudnnConfig class - cudnn_test::CudnnConfig function = function_config.get(); - function.set_num_test(options.num_test); - function.set_warm_up(options.warm_up); - function.set_num_in_step(options.num_in_step); - function.set_random_seed(options.random_seed); - function.set_auto_algo(options.auto_algo); - if (function.get_input_type() == CUDNN_DATA_FLOAT && function.get_conv_type() == CUDNN_DATA_FLOAT) { - auto p_function = get_cudnn_function_pointer(function); - p_function->benchmark(); - delete p_function; - } else { - if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_FLOAT) { - auto p_function = get_cudnn_function_pointer(function); - p_function->benchmark(); - delete p_function; - } else { - if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_HALF) { - auto p_function = get_cudnn_function_pointer(function); - p_function->benchmark(); - delete p_function; - } else { - throw "invalid input and conv type"; - } - } - } - } catch (std::exception &e) { - std::cout << "Error: " << e.what() << std::endl; + json function_config = json::parse(options.para_info_json); + cudnn_test::CudnnConfig function = function_config.get(); + function.set_num_test(options.num_test); + function.set_warm_up(options.warm_up); + function.set_num_in_step(options.num_in_step); + function.set_random_seed(options.random_seed); + function.set_auto_algo(options.auto_algo); + if (function.get_input_type() == CUDNN_DATA_FLOAT && function.get_conv_type() == CUDNN_DATA_FLOAT) { + std::unique_ptr> p_function(get_cudnn_function_pointer(function)); + p_function->benchmark(); + } else if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_FLOAT) { + std::unique_ptr> p_function(get_cudnn_function_pointer(function)); + p_function->benchmark(); + } else if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_HALF) { + std::unique_ptr> p_function(get_cudnn_function_pointer(function)); + p_function->benchmark(); + } else { + throw std::invalid_argument("invalid input and conv type"); } } } // namespace cudnn_test diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp index 26b8877c2..8039c709a 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp @@ -57,30 +57,56 @@ void cudnn_handle_free(cudnnHandle_t *cudnn_handle) { CHECK_CUDNN_ERROR(cudnnDes * @param random_seed the random seed to generate random data */ template void rand(T **input, std::vector dims_, int random_seed) { - throw "unsupported rand data type"; + throw std::invalid_argument("unsupported rand data type"); } -template <> void rand(float **input, std::vector dims_, int random_seed) { - int size = std::accumulate(dims_.begin(), dims_.end(), 1, std::multiplies()); +template <> void rand(float **input, size_t size, int random_seed) { + if (size == 0 || size > std::numeric_limits::max() / sizeof(float)) { + throw std::invalid_argument("invalid float allocation size"); + } CUDA_SAFE_CALL(cudaMalloc((void **)input, sizeof(float) * size)); float *host_input; CUDA_SAFE_CALL(cudaMallocHost(&host_input, sizeof(float) * size)); + std::unique_ptr host_owner(host_input, cudaFreeHost); srand(random_seed); - for (int i = 0; i < size; i++) { - host_input[i] = (float)std::rand() / (float)(RAND_MAX); + for (size_t index = 0; index < size; ++index) { + host_input[index] = (float)std::rand() / (float)(RAND_MAX); } // copy input data from host to device CUDA_SAFE_CALL(cudaMemcpy(*input, host_input, sizeof(float) * size, cudaMemcpyHostToDevice)); - CUDA_SAFE_CALL(cudaFreeHost(host_input)); } -template <> void rand(half **input, std::vector dims_, int random_seed) { - int size = std::accumulate(dims_.begin(), dims_.end(), 1, std::multiplies()); +template <> void rand(half **input, size_t size, int random_seed) { + if (size == 0 || size > std::numeric_limits::max() / sizeof(half)) { + throw std::invalid_argument("invalid half allocation size"); + } CUDA_SAFE_CALL(cudaMalloc((void **)input, sizeof(half) * size)); half *host_input; CUDA_SAFE_CALL(cudaMallocHost(&host_input, sizeof(half) * size)); - for (int i = 0; i < size; i++) { - host_input[i] = __float2half((float)std::rand() / (float)(RAND_MAX)); + std::unique_ptr host_owner(host_input, cudaFreeHost); + srand(random_seed); + for (size_t index = 0; index < size; ++index) { + host_input[index] = __float2half((float)std::rand() / (float)(RAND_MAX)); + } + CUDA_SAFE_CALL(cudaMemcpy(*input, host_input, sizeof(half) * size, cudaMemcpyHostToDevice)); +} + +size_t contiguous_elements(const std::vector &dims) { + if (dims.empty()) + throw std::invalid_argument("allocation dimensions must not be empty"); + size_t elements = 1; + for (int dimension : dims) { + if (dimension <= 0 || elements > std::numeric_limits::max() / static_cast(dimension)) { + throw std::invalid_argument("invalid or overflowing allocation dimensions"); + } + elements *= static_cast(dimension); } - CUDA_SAFE_CALL(cudaMemcpy(host_input, *input, sizeof(half) * size, cudaMemcpyHostToDevice)); - CUDA_SAFE_CALL(cudaFreeHost(host_input)); + return elements; +} + +template <> void rand(float **input, std::vector dims_, int random_seed) { + rand(input, contiguous_elements(dims_), random_seed); +} + +template <> void rand(half **input, std::vector dims_, int random_seed) { + rand(input, contiguous_elements(dims_), random_seed); } } // namespace cudnn_test diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h index 7047adbb4..3a63f0dcd 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h @@ -8,8 +8,11 @@ #pragma once #include +#include #include +#include #include +#include #include #include @@ -47,6 +50,26 @@ void cudnn_handle_free(cudnnHandle_t *cudnn_handle); * @param random_seed the random seed to generate random data */ template void rand(T **input, std::vector dims_, int random_seed); +template void rand(T **input, size_t elements, int random_seed); + +inline size_t tensor_storage_size(const std::vector &dims, const std::vector &strides) { + if (dims.empty() || dims.size() != strides.size()) { + throw std::invalid_argument("tensor dimensions and strides must have the same nonzero rank"); + } + size_t elements = 1; + for (size_t axis = 0; axis < dims.size(); ++axis) { + if (dims[axis] <= 0 || strides[axis] <= 0) { + throw std::invalid_argument("tensor dimensions and strides must be positive"); + } + const size_t dimension = static_cast(dims[axis] - 1); + const size_t stride = static_cast(strides[axis]); + if (dimension > (std::numeric_limits::max() - elements) / stride) { + throw std::invalid_argument("tensor storage size overflows size_t"); + } + elements += dimension * stride; + } + return elements; +} /** * @brief Malloc cuda memory and fill in zero * @tparam T @@ -98,8 +121,9 @@ template class TensorDescriptorNd { std::shared_ptr desc_; struct TensorDescriptorNdDeleter { - void operator()(cudnnTensorDescriptor_t *desc) { - CHECK_CUDNN_ERROR(cudnnDestroyTensorDescriptor(*desc)); + void operator()(cudnnTensorDescriptor_t *desc) noexcept { + if (*desc != nullptr) + cudnnDestroyTensorDescriptor(*desc); delete desc; } }; @@ -107,7 +131,8 @@ template class TensorDescriptorNd { public: TensorDescriptorNd() {} TensorDescriptorNd(const std::vector &dim, const std::vector &stride) - : desc_(new cudnnTensorDescriptor_t, TensorDescriptorNdDeleter()) { + : desc_(new cudnnTensorDescriptor_t{}, TensorDescriptorNdDeleter()) { + tensor_storage_size(dim, stride); cudnnDataType_t type; get_tensor_type(type); @@ -126,8 +151,9 @@ template class FilterDescriptorNd { std::shared_ptr desc_; struct FilterDescriptorNdDeleter { - void operator()(cudnnFilterDescriptor_t *desc) { - CHECK_CUDNN_ERROR(cudnnDestroyFilterDescriptor(*desc)); + void operator()(cudnnFilterDescriptor_t *desc) noexcept { + if (*desc != nullptr) + cudnnDestroyFilterDescriptor(*desc); delete desc; } }; @@ -135,7 +161,10 @@ template class FilterDescriptorNd { public: FilterDescriptorNd() {} - FilterDescriptorNd(const std::vector &dim) : desc_(new cudnnFilterDescriptor_t, FilterDescriptorNdDeleter()) { + FilterDescriptorNd(const std::vector &dim) + : desc_(new cudnnFilterDescriptor_t{}, FilterDescriptorNdDeleter()) { + if (dim.empty()) + throw std::invalid_argument("filter dimensions must not be empty"); cudnnTensorFormat_t tensor_format; get_tensor_format(tensor_format); cudnnDataType_t type; @@ -156,8 +185,9 @@ template class ConvolutionDescriptor { std::shared_ptr desc_; struct ConvolutionDescriptorDeleter { - void operator()(cudnnConvolutionDescriptor_t *desc) { - CHECK_CUDNN_ERROR(cudnnDestroyConvolutionDescriptor(*desc)); + void operator()(cudnnConvolutionDescriptor_t *desc) noexcept { + if (*desc != nullptr) + cudnnDestroyConvolutionDescriptor(*desc); delete desc; } }; @@ -166,7 +196,12 @@ template class ConvolutionDescriptor { ConvolutionDescriptor() {} ConvolutionDescriptor(int array_length, const std::vector &padA, const std::vector &filter_strideA, const std::vector &dilationA, cudnnConvolutionMode_t mode) - : desc_(new cudnnConvolutionDescriptor_t, ConvolutionDescriptorDeleter()) { + : desc_(new cudnnConvolutionDescriptor_t{}, ConvolutionDescriptorDeleter()) { + if (array_length <= 0 || padA.size() != static_cast(array_length) || + filter_strideA.size() != static_cast(array_length) || + dilationA.size() != static_cast(array_length)) { + throw std::invalid_argument("convolution dimension arrays have different lengths"); + } cudnnDataType_t type; get_tensor_type(type); diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_binary.py b/tests/benchmarks/micro_benchmarks/test_cudnn_binary.py new file mode 100644 index 000000000..f58bbe3d9 --- /dev/null +++ b/tests/benchmarks/micro_benchmarks/test_cudnn_binary.py @@ -0,0 +1,129 @@ +"""Run native cuDNN execution checks against SB_CUDNN_TEST_BINARY.""" + +import json +import math +import os +import subprocess +import unittest + + +@unittest.skipUnless( + os.environ.get('SB_CUDNN_TEST_BINARY'), 'Set SB_CUDNN_TEST_BINARY to the compiled native benchmark.' +) +class CudnnBinaryTests(unittest.TestCase): + """Exercise the actual native binary and its controlled error exits.""" + + def configuration(self, name='cudnnConvolutionForward', input_type=0, conv_type=0): + """Create a bounded convolution configuration.""" + return { + 'name': name, + 'algo': 0, + 'inputDims': [1, 2, 3, 3], + 'inputStride': [18, 9, 3, 1], + 'outputDims': [1, 2, 3, 3], + 'outputStride': [18, 9, 3, 1], + 'filterDims': [2, 2, 1, 1], + 'inputType': input_type, + 'convType': conv_type, + 'arrayLength': 2, + 'padA': [0, 0], + 'filterStrideA': [1, 1], + 'dilationA': [1, 1], + 'mode': 1, + 'tensorOp': False, + } + + def run_binary(self, configuration): + """Execute a small case with captured output and a finite deadline.""" + value = json.dumps(configuration) if isinstance(configuration, dict) else configuration + return subprocess.run( + [os.environ['SB_CUDNN_TEST_BINARY'], '--num_test', '2', '--warm_up', '1', '--num_in_step', '1', + '--random_seed', '33931', '--config_json', value], + capture_output=True, text=True, timeout=30 + ) + + def test_convolution_storage_compute_combinations(self): + """Execute supported storage and compute types in all directions.""" + for name in ('cudnnConvolutionForward', 'cudnnConvolutionBackwardData', 'cudnnConvolutionBackwardFilter'): + for input_type, conv_type in ((0, 0), (2, 0)): + with self.subTest(name=name, input_type=input_type, conv_type=conv_type): + result = self.run_binary(self.configuration(name, input_type, conv_type)) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn('Error', result.stdout + result.stderr) + rows = [line for line in result.stdout.splitlines() if line.startswith('[raw_data]:')] + self.assertEqual(len(rows), 1, result.stdout) + samples = [float(value) for value in rows[0].split(':', 1)[1].split(',') if value.strip()] + self.assertEqual(len(samples), 2) + self.assertTrue(all(math.isfinite(value) and value > 0 for value in samples)) + + def test_half_compute_support_or_controlled_rejection(self): + """Keep half-compute capability rejection distinct from an abort.""" + for name in ('cudnnConvolutionForward', 'cudnnConvolutionBackwardData', 'cudnnConvolutionBackwardFilter'): + with self.subTest(name=name): + result = self.run_binary(self.configuration(name, 2, 2)) + if 'CUDNN_STATUS_NOT_SUPPORTED' in result.stdout: + self.assertGreater(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn('[raw_data]:', result.stdout) + else: + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('[raw_data]:', result.stdout) + self.assertNotIn('Error:', result.stdout) + + def test_invalid_json_is_a_controlled_failure(self): + """Reject invalid JSON without timing output.""" + result = self.run_binary('{') + self.assertGreater(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('Error:', result.stdout) + self.assertNotIn('[raw_data]:', result.stdout) + + def test_invalid_type_pair_is_a_controlled_failure(self): + """Reject an unsupported storage and compute type pair.""" + result = self.run_binary(self.configuration(input_type=0, conv_type=2)) + self.assertGreater(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('Error:', result.stdout) + self.assertNotIn('[raw_data]:', result.stdout) + + def test_missing_required_field_is_a_controlled_failure(self): + """Reject an incomplete configuration without a false successful exit.""" + config = self.configuration() + del config['filterDims'] + result = self.run_binary(config) + self.assertGreater(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn('[raw_data]:', result.stdout) + + def test_invalid_function_is_a_controlled_failure(self): + """Reject unknown function names through the normal error handler.""" + result = self.run_binary(self.configuration(name='not-a-cudnn-function')) + self.assertGreater(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('Error:', result.stdout) + self.assertNotIn('[raw_data]:', result.stdout) + + def test_noncontiguous_tensor_strides_execute_or_reject_cleanly(self): + """Respect strided storage when supported and retain capability failures.""" + for name in ('cudnnConvolutionForward', 'cudnnConvolutionBackwardData', 'cudnnConvolutionBackwardFilter'): + with self.subTest(name=name): + config = self.configuration(name) + config['inputStride'] = [40, 20, 5, 1] + config['outputStride'] = [40, 20, 5, 1] + result = self.run_binary(config) + if 'CUDNN_STATUS_NOT_SUPPORTED' in result.stdout: + self.assertGreater(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn('[raw_data]:', result.stdout) + else: + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('[raw_data]:', result.stdout) + + def test_invalid_descriptor_lengths_are_controlled_failures(self): + """Reject incomplete descriptor arrays before unsafe API access.""" + for field, value in (('inputStride', [18]), ('padA', [0]), ('filterDims', [])): + with self.subTest(field=field): + config = self.configuration() + config[field] = value + result = self.run_binary(config) + self.assertGreater(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('Error:', result.stdout) + self.assertNotIn('[raw_data]:', result.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp b/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp new file mode 100644 index 000000000..cfd14fbaa --- /dev/null +++ b/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp @@ -0,0 +1,211 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cudnn_config.h" +#include "cudnn_function.h" + +using cudnn_test::check_cuda; +using cudnn_test::throw_cudnn_err; + +void require(bool condition, const char *message) { + if (!condition) + throw std::runtime_error(message); +} + +void test_independent_types() { + cudnn_test::CudnnConfig config{}; + config.set_input_type(CUDNN_DATA_HALF); + config.set_conv_type(CUDNN_DATA_FLOAT); + require(config.get_input_type() == CUDNN_DATA_HALF, "compute type overwrote half storage type"); + require(config.get_conv_type() == CUDNN_DATA_FLOAT, "compute type was not stored independently"); + config.set_conv_type(CUDNN_DATA_HALF); + config.set_input_type(CUDNN_DATA_FLOAT); + require(config.get_conv_type() == CUDNN_DATA_HALF, "storage type overwrote compute type"); + require(config.get_input_type() == CUDNN_DATA_FLOAT, "storage type did not change"); +} + +void test_half_initialization() { + constexpr int count = 257; + constexpr int seed = 33931; + std::vector expected(count); + std::srand(seed); + for (auto &value : expected) + value = __half2float(__float2half(static_cast(std::rand()) / RAND_MAX)); + std::vector first; + for (int repeat = 0; repeat < 2; ++repeat) { + std::srand(seed + repeat + 1); + half *device = nullptr; + try { + cudnn_test::rand(&device, {count}, seed); + std::vector host(count); + CUDA_SAFE_CALL(cudaMemcpy(host.data(), device, count * sizeof(half), cudaMemcpyDeviceToHost)); + std::vector actual(count); + for (int index = 0; index < count; ++index) + actual[index] = __half2float(host[index]); + require(actual == expected, "half data does not match the supplied seed and host-to-device copy"); + if (repeat == 0) + first = actual; + else + require(actual == first, "half initialization depends on ambient RNG state"); + CUDA_SAFE_CALL(cudaFree(device)); + } catch (...) { + if (device != nullptr) + cudaFree(device); + throw; + } + } +} + +void test_descriptor_types() { + cudnn_test::TensorDescriptorNd input({1, 2, 3, 3}, {18, 9, 3, 1}); + cudnn_test::FilterDescriptorNd filter({2, 2, 1, 1}); + cudnn_test::ConvolutionDescriptor convolution(2, {0, 0}, {1, 1}, {1, 1}, CUDNN_CROSS_CORRELATION); + cudnnDataType_t storage, filter_type, compute; + cudnnTensorFormat_t format; + cudnnConvolutionMode_t mode; + int rank, dims[4], strides[4], padding[2], dilation[2], conv_stride[2]; + CHECK_CUDNN_ERROR(cudnnGetTensorNdDescriptor(input.desc(), 4, &storage, &rank, dims, strides)); + CHECK_CUDNN_ERROR(cudnnGetFilterNdDescriptor(filter.desc(), 4, &filter_type, &format, &rank, dims)); + CHECK_CUDNN_ERROR( + cudnnGetConvolutionNdDescriptor(convolution.desc(), 2, &rank, padding, conv_stride, dilation, &mode, &compute)); + require(storage == CUDNN_DATA_HALF && filter_type == CUDNN_DATA_HALF && compute == CUDNN_DATA_FLOAT, + "actual cuDNN descriptors do not preserve half storage with float compute"); +} + +cudnn_test::CudnnConfig workspace_config() { + cudnn_test::CudnnConfig config{}; + config.set_input_dims({1, 2, 3, 3}); + config.set_input_stride({18, 9, 3, 1}); + config.set_output_dims({1, 2, 3, 3}); + config.set_output_stride({18, 9, 3, 1}); + config.set_filter_dims({2, 2, 1, 1}); + config.set_array_length(2); + config.set_padA({0, 0}); + config.set_filter_strideA({1, 1}); + config.set_dilationA({1, 1}); + config.set_mode(CUDNN_CROSS_CORRELATION); + config.set_use_tensor_op(false); + config.set_auto_algo(false); + return config; +} + +class WorkspaceProbe : public cudnn_test::CudnnFunction { + size_t requested_bytes_; + + void get_workspace_size() override { fwd_workspace_size_ = requested_bytes_; } + + public: + WorkspaceProbe(cudnn_test::CudnnConfig &config, size_t requested_bytes) + : CudnnFunction(config), requested_bytes_(requested_bytes) { + x = nullptr; + filter = nullptr; + h = nullptr; + } + + void prepare() { prepare_for_function(); } + void prepare_data() { prepare_input(); } + CUdeviceptr input() const { return reinterpret_cast(x); } + CUdeviceptr workspace() const { return reinterpret_cast(fwd_workspace_); } +}; + +void check_workspace_size(size_t bytes) { + auto config = workspace_config(); + WorkspaceProbe function(config, bytes); + function.prepare(); + CUdeviceptr allocation; + size_t allocated_bytes = 0; + require(cuMemGetAddressRange(&allocation, &allocated_bytes, function.workspace()) == CUDA_SUCCESS, + "workspace does not have a valid device allocation"); + require(allocated_bytes >= bytes, "workspace was rounded down below requested bytes"); +} + +void test_workspace_byte_size() { check_workspace_size(13); } +void test_single_byte_workspace() { check_workspace_size(1); } + +void test_workspace_released() { + auto config = workspace_config(); + CUdeviceptr pointer; + { + WorkspaceProbe function(config, 4096); + function.prepare(); + pointer = function.workspace(); + } + CUdeviceptr allocation; + size_t bytes; + require(cuMemGetAddressRange(&allocation, &bytes, pointer) != CUDA_SUCCESS, + "workspace allocation remains live after destruction"); +} + +void test_unprepared_destruction() { + auto config = workspace_config(); + cudnn_test::CudnnFunction function(config); +} + +void test_strided_allocation() { + auto config = workspace_config(); + config.set_input_stride({40, 20, 5, 1}); + config.set_random_seed(33931); + WorkspaceProbe function(config, 0); + function.prepare_data(); + CUdeviceptr allocation; + size_t bytes = 0; + require(cuMemGetAddressRange(&allocation, &bytes, function.input()) == CUDA_SUCCESS, + "strided input allocation is missing"); + require(bytes >= 33 * sizeof(float), "input allocation does not cover the descriptor stride extent"); +} + +void test_invalid_shape_rejected() { + bool rejected = false; + try { + cudnn_test::TensorDescriptorNd descriptor({1, 2, 3, 3}, {18}); + } catch (const std::invalid_argument &) { + rejected = true; + } + require(rejected, "mismatched stride rank was passed to cuDNN"); + rejected = false; + try { + cudnn_test::ConvolutionDescriptor descriptor(2, {0}, {1, 1}, {1, 1}, CUDNN_CROSS_CORRELATION); + } catch (const std::invalid_argument &) { + rejected = true; + } + require(rejected, "mismatched convolution arrays were passed to cuDNN"); +} + +int main(int argc, char **argv) { + const bool memcheck = argc == 2 && std::string(argv[1]) == "--memcheck"; + if (argc > 1 && !memcheck) + return 2; + std::cout.setf(std::ios::unitbuf); + int failures = 0; + const std::vector> tests = { + {"independent_types", test_independent_types}, + {"half_initialization", test_half_initialization}, + {"descriptor_types", test_descriptor_types}, + {"workspace_byte_size", test_workspace_byte_size}, + {"single_byte_workspace", test_single_byte_workspace}, + {"workspace_released", test_workspace_released}, + {"unprepared_destruction", test_unprepared_destruction}, + {"strided_allocation", test_strided_allocation}, + {"invalid_shape_rejected", test_invalid_shape_rejected}, + }; + for (const auto &test : tests) { + if (memcheck && std::string(test.first) == "workspace_released") { + std::cout << test.first << ": skipped negative driver query; use sanitizer leak check\n"; + continue; + } + try { + test.second(); + std::cout << test.first << ": passed\n"; + } catch (const std::exception &error) { + ++failures; + std::cout << test.first << ": failed: " << error.what() << '\n'; + } + } + return failures == 0 ? 0 : 1; +} \ No newline at end of file diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py b/tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py new file mode 100644 index 000000000..2358b0a2f --- /dev/null +++ b/tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py @@ -0,0 +1,180 @@ +"""CPU-only tests for cuDNN timing output validation.""" + +import json +import subprocess +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, call, patch + +from superbench.benchmarks import ReturnCode +from superbench.benchmarks.micro_benchmarks.cudnn_function import CudnnBenchmark + + +class CudnnRawResultTests(unittest.TestCase): + """Test parsing without preprocessing or launching the native benchmark.""" + + def setUp(self): + """Provide only the state consumed by the timing parser.""" + self.benchmark = CudnnBenchmark.__new__(CudnnBenchmark) + self.benchmark._name = 'cudnn-function' + self.benchmark._curr_run_index = 0 + self.benchmark._args = SimpleNamespace(num_steps=3, log_raw_data=False) + self.benchmark._result = Mock(spec=['add_raw_data', 'add_result']) + configuration = { + 'tensorOp': True, + 'name': 'cudnnConvolutionForward', + 'inputDims': [1, 2, 3, 3], + 'algo': 1, + } + self.benchmark._commands = ["cudnn_benchmark --config_json '{}'".format(json.dumps(configuration))] + self.metric = 'name_cudnnconvolutionforward_algo_1_inputdims_[1_2_3_3]_tensorop_true_time' + self.valid_row = '[raw_data]: 0.001,0.002,0.003,' + + def assert_valid_output(self, raw_output, samples, mean_time): + """Check successful metrics, units, and unmodified raw output.""" + self.benchmark._result.reset_mock() + self.assertIs(self.benchmark._process_raw_result(0, raw_output), True) + self.benchmark._result.add_result.assert_called_once_with(self.metric, mean_time) + self.assertEqual( + self.benchmark._result.add_raw_data.call_args_list, + [ + call('raw_output_0', raw_output, self.benchmark._args.log_raw_data), + call(self.metric, samples, self.benchmark._args.log_raw_data), + ] + ) + + def assert_invalid_output(self, raw_output): + """Require failure without any partial timing data or good metric.""" + self.benchmark._result.reset_mock() + self.assertIs(self.benchmark._process_raw_result(0, raw_output), False) + self.benchmark._result.add_result.assert_called_once_with(self.metric, -1) + self.benchmark._result.add_raw_data.assert_called_once_with( + 'raw_output_0', raw_output, self.benchmark._args.log_raw_data + ) + + def test_valid_native_output(self): + """Keep naming, milliseconds-to-microseconds scaling, and logging flags.""" + raw_output = 'cuDNN benchmark\n{}\nBenchmark completed\n'.format(self.valid_row) + for log_raw_data in (False, True): + with self.subTest(log_raw_data=log_raw_data): + self.benchmark._args.log_raw_data = log_raw_data + self.assert_valid_output(raw_output, [0.001, 0.002, 0.003], 2.0) + + def test_valid_without_trailing_comma(self): + """Do not drop the last sample when the optional comma is absent.""" + self.assert_valid_output('[raw_data]: 0.001,0.002,0.003', [0.001, 0.002, 0.003], 2.0) + + def test_valid_with_whitespace(self): + """Allow whitespace around the native values and trailing comma.""" + self.assert_valid_output('[raw_data]: \t1e-3, 2e-3, 3e-3, \t\n', [0.001, 0.002, 0.003], 2.0) + + def test_absent_timing_record(self): + """Empty or informational output cannot report success.""" + for raw_output in ('', '\n \n', 'cuDNN benchmark completed\n'): + with self.subTest(raw_output=raw_output): + self.assert_invalid_output(raw_output) + + def test_empty_timing_record(self): + """A timing marker alone is not a measurement.""" + for raw_output in ('[raw_data]:', '[raw_data]: \n', '[raw_data]: ,', '[raw_data]: \t, \t'): + with self.subTest(raw_output=raw_output): + self.assert_invalid_output(raw_output) + + def test_non_finite_samples(self): + """Reject NaN, infinity, and numbers that overflow float parsing.""" + for sample in ('nan', 'NaN', 'inf', '-inf', '+Inf', '1e309', '-1e309'): + with self.subTest(sample=sample): + self.assert_invalid_output('[raw_data]: 0.001,{},0.003,'.format(sample)) + + def test_non_positive_samples(self): + """Every sample must be positive, including after float underflow.""" + for sample in ('0', '0.0', '-0.0', '-0.001', '1e-400'): + with self.subTest(sample=sample): + self.assert_invalid_output('[raw_data]: 0.001,{},0.003,'.format(sample)) + + def test_wrong_sample_count(self): + """Require exactly num_steps samples, with or without a final comma.""" + for samples in ('0.001,', '0.001,0.002,', '0.001,0.002,0.003,0.004,', '0.001,0.002,0.003,0.004'): + with self.subTest(samples=samples): + self.assert_invalid_output('[raw_data]: ' + samples) + + def test_non_positive_num_steps(self): + """Zero or negative requested steps cannot produce a valid record.""" + for num_steps in (0, -1): + for raw_output in ('[raw_data]: ', self.valid_row): + with self.subTest(num_steps=num_steps, raw_output=raw_output): + self.benchmark._args.num_steps = num_steps + self.assert_invalid_output(raw_output) + + def test_duplicate_timing_records(self): + """Reject a second record without retaining the first measurement.""" + for second_row in (self.valid_row, '[raw_data]: 0.004,0.005,0.006,', '[raw_data]: '): + with self.subTest(second_row=second_row): + self.assert_invalid_output(self.valid_row + '\n' + second_row) + + def test_malformed_timing_record(self): + """Do not discard invalid tokens or extra delimiters as a final comma.""" + for raw_output in ( + '[raw_data] 0.001,0.002,0.003,', + '[raw_data]: 0.001,invalid,0.003,', + '[raw_data]: 0.001,,0.003,', + '[raw_data]: ,0.001,0.002,0.003,', + '[raw_data]: 0.001,0.002,0.003,,', + '[raw_data]: 0.001,0.002,0.003, ,', + '[raw_data]: 0.001,0.002,0.003,garbage', + ): + with self.subTest(raw_output=raw_output): + self.assert_invalid_output(raw_output) + + def test_error_before_or_after_valid_record(self): + """An error anywhere in stdout invalidates otherwise valid timings.""" + for raw_output in ( + 'Error: CUDNN_STATUS_NOT_SUPPORTED\n' + self.valid_row, + self.valid_row + '\nError: cuDNN call failed', + ): + with self.subTest(raw_output=raw_output): + self.assert_invalid_output(raw_output) + + def test_error_without_timing_record(self): + """Keep the existing failure marker when only an error is reported.""" + self.assert_invalid_output('Error: CUDNN_STATUS_NOT_SUPPORTED\n') + + def test_unit_conversion_overflow(self): + """Finite input samples must not produce an infinite scaled metric.""" + self.assert_invalid_output('[raw_data]: 1e306,1e306,1e306,') + + def test_large_finite_scaled_metric(self): + """Do not reject large timings whose scaled mean remains finite.""" + self.assert_valid_output('[raw_data]: 1e300,1e300,1e300,', [1e300, 1e300, 1e300], 1e300 * 1000) + + def test_tolerant_invoke_keeps_failure_and_later_successful_cases(self): + """A native rejection must not erase valid timings or become overall success.""" + self.benchmark._args.tolerant_fail = True + self.benchmark._args.log_flushing = False + self.benchmark._args.bin_dir = '/tmp' + self.benchmark._result = Mock(spec=['add_raw_data', 'add_result', 'set_return_code']) + self.benchmark._commands *= 3 + outcomes = [subprocess.CompletedProcess('binary', 0, self.valid_row), + subprocess.CompletedProcess('binary', 255, 'Error: CUDNN_STATUS_NOT_SUPPORTED'), + subprocess.CompletedProcess('binary', 0, self.valid_row)] + with patch('superbench.benchmarks.micro_benchmarks.micro_base.run_command', side_effect=outcomes) as execute: + self.assertFalse(self.benchmark._benchmark()) + self.assertEqual(execute.call_count, 3) + self.benchmark._result.set_return_code.assert_called_once_with(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE) + self.assertEqual(self.benchmark._result.add_result.call_args_list, [call(self.metric, 2.0)] * 2) + + def test_zero_exit_empty_output_sets_parsing_failure(self): + """An empty successful process is not a successful benchmark measurement.""" + self.benchmark._args.tolerant_fail = True + self.benchmark._args.log_flushing = False + self.benchmark._args.bin_dir = '/tmp' + self.benchmark._result = Mock(spec=['add_raw_data', 'add_result', 'set_return_code']) + with patch('superbench.benchmarks.micro_benchmarks.micro_base.run_command', + return_value=subprocess.CompletedProcess('binary', 0, '')): + self.assertFalse(self.benchmark._benchmark()) + self.benchmark._result.set_return_code.assert_called_once_with(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.benchmark._result.add_result.assert_called_once_with(self.metric, -1) + + +if __name__ == '__main__': + unittest.main() From 6e964cc6279ef1f3b8880f6d47891f5208f354f7 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Tue, 8 Sep 2026 19:48:31 +0000 Subject: [PATCH 2/3] Benchmarks: Narrow cuDNN fix to precision and initialization Keep independent storage and compute types, seeded half initialization, and two direct native regressions. Defer documentation, parser, resource, stride, and exception-handling changes to separate work. --- .../benchmarks/micro-benchmarks.md | 15 -- .../micro_benchmarks/cudnn_function.py | 30 ++- .../cudnn_function/CMakeLists.txt | 2 +- .../micro_benchmarks/cudnn_function/README.md | 61 ------ .../cudnn_function/cudnn_config.h | 3 +- .../cudnn_function/cudnn_function.h | 35 ++-- .../cudnn_function/cudnn_function_helper.h | 51 +++-- .../cudnn_function/cudnn_helper.cpp | 47 ++--- .../cudnn_function/cudnn_helper.h | 53 +----- .../micro_benchmarks/test_cudnn_binary.py | 129 ------------- .../test_cudnn_data_types.cpp | 143 +------------- .../micro_benchmarks/test_cudnn_raw_result.py | 180 ------------------ 12 files changed, 81 insertions(+), 668 deletions(-) delete mode 100644 superbench/benchmarks/micro_benchmarks/cudnn_function/README.md delete mode 100644 tests/benchmarks/micro_benchmarks/test_cudnn_binary.py delete mode 100644 tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index a8ef84b3c..d56965a7c 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -110,21 +110,6 @@ The supported functions for cuDNN are as follows: |-----------------------------------------------------------|-----------|------------------------------------------------------------------| | cudnn-function/name\_${function_name}\_${parameters}_time | time (us) | The mean time to execute the cudnn function with the parameters. | -#### Precision and compatibility - -`inputType` selects tensor and filter storage, while `convType` independently selects convolution compute precision. -The cuDNN enum values `0` and `2` represent FP32 and FP16, respectively; supported combinations and algorithms depend on the GPU and cuDNN version. - -Versions with the aliased storage/compute-field defect execute cases requesting `inputType: 2, convType: 0` with FP32 storage instead of FP16 storage. -This affects nine of the eighteen default cuDNN configurations, not other SuperBench benchmarks. -After applying the fix, rebuild the native benchmark and helper library and regenerate baselines for these cases using the repaired source/image. -Do not compare repaired FP16 measurements with the old effective-FP32 baselines just because their metric names match. -Metric names, microsecond units, and the host-wall timing loop are unchanged. - -Native execution failures and missing, malformed, duplicate, or non-finite timing records are not successful measurements. -Keep unsupported configurations visible as failures; do not silently accept them as timing data. -See the [cuDNN regression checks](../../../superbench/benchmarks/micro_benchmarks/cudnn_function/README.md) for focused validation commands. - ### `tensorrt-inference` #### Introduction diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function.py b/superbench/benchmarks/micro_benchmarks/cudnn_function.py index 1a9da676e..3bc601742 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function.py +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function.py @@ -429,22 +429,18 @@ def _process_raw_result(self, cmd_idx, raw_output): metric = metric + '_' + key + '_' + str(cmd_config[key]) metric = metric.replace(' ', '').replace(',', '_') - if 'Error' in raw_output: - raise ValueError('Error reported in cuDNN output.') - timing_records = [line for line in lines if '[raw_data]' in line] - if len(timing_records) != 1: - raise ValueError('Expected exactly one timing record.') - raw_data = timing_records[0].split('[raw_data]:', 1)[1].strip() - if raw_data.endswith(','): - raw_data = raw_data[:-1] - raw_data = [float(item) for item in raw_data.split(',')] - if len(raw_data) != self._args.num_steps or not all(0 < sample < float('inf') for sample in raw_data): - raise ValueError('Expected exactly {} finite positive timing samples.'.format(self._args.num_steps)) - mean_time = statistics.mean(raw_data) * 1000 - if not 0 < mean_time < float('inf'): - raise ValueError('Expected a finite positive mean time after unit conversion.') - self._result.add_result(metric.lower() + '_time', mean_time) - self._result.add_raw_data(metric.lower() + '_time', raw_data, self._args.log_raw_data) + error = False + raw_data = [] + for line in lines: + if '[raw_data]' in line: + raw_data = line[line.index('[raw_data]: ') + len('[raw_data]: '):] + raw_data = raw_data.split(',') + raw_data.pop() + raw_data = [float(item) for item in raw_data] + self._result.add_result(metric.lower() + '_time', statistics.mean(raw_data) * 1000) + self._result.add_raw_data(metric.lower() + '_time', raw_data, self._args.log_raw_data) + if 'Error' in line: + error = True except BaseException as e: logger.error( 'Cannot extract results from cudnn functions - round: {}, index of cmd: {}, \ @@ -452,6 +448,8 @@ def _process_raw_result(self, cmd_idx, raw_output): self._curr_run_index, cmd_idx, self._name, raw_output, str(e) ) ) + error = True + if error: logger.error( 'Error in running cudnn test - round: {}, index of cmd: {}, benchmark: {}, raw data: {}'.format( self._curr_run_index, cmd_idx, self._name, raw_output diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt index b04bec2d1..902569257 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt @@ -36,7 +36,7 @@ if(CUDAToolkit_FOUND) if(EXISTS "${CUDNN_DATA_TYPES_TEST_SOURCE}") add_executable(cudnn_data_types_test EXCLUDE_FROM_ALL ${CUDNN_DATA_TYPES_TEST_SOURCE}) target_include_directories(cudnn_data_types_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) - target_link_libraries(cudnn_data_types_test ${TARGET_NAME} CUDA::cudart CUDA::cuda_driver ${CUDNN_LIBRARY}) + target_link_libraries(cudnn_data_types_test ${TARGET_NAME} CUDA::cudart ${CUDNN_LIBRARY}) endif() install(TARGETS cudnn_benchmark ${TARGET_NAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib) diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/README.md b/superbench/benchmarks/micro_benchmarks/cudnn_function/README.md deleted file mode 100644 index 33624e65a..000000000 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# cuDNN Regression Checks - -Run these commands from the repository root in an environment with the supported -CUDA toolkit, cuDNN development libraries, C++ compiler, CMake, and a compatible -NVIDIA GPU. Python parser checks require the normal SuperBench Python dependencies -but do not launch a GPU workload. CMake fetches the existing pinned JSON dependency -unless it is supplied through `FETCHCONTENT_SOURCE_DIR_JSON`. - -## Build And Run - -```bash -cmake -S superbench/benchmarks/micro_benchmarks/cudnn_function \ - -B build/cudnn-tests -DCMAKE_BUILD_TYPE=Release -cmake --build build/cudnn-tests \ - --target cudnn_benchmark cudnn_data_types_test --parallel 2 -CUDA_VISIBLE_DEVICES=0 build/cudnn-tests/cudnn_data_types_test -CUDA_VISIBLE_DEVICES=0 \ - SB_CUDNN_TEST_BINARY="$PWD/build/cudnn-tests/cudnn_benchmark" \ - python3 tests/benchmarks/micro_benchmarks/test_cudnn_binary.py -v -python3 -m unittest discover -s tests/benchmarks/micro_benchmarks \ - -p test_cudnn_raw_result.py -v -``` - -With CUDA 13 installations that place CCCL headers under the toolkit's `include/cccl` -directory, add `-DCMAKE_CXX_FLAGS=-I/usr/local/cuda/include/cccl` when configuring -(adjust the toolkit path). Use the toolkit and architecture flags appropriate to -the target GPU; a build on one architecture is not runtime qualification of another. - -The native test target is excluded from the default build and installation. It is -available when the repository's test source is present, so native-source-only -packages can still configure and build without the tests. The CLI tests skip when -`SB_CUDNN_TEST_BINARY` is unset; set it explicitly for a real native gate. - -## Coverage And Limits - -- Native checks cover independent storage/compute fields, descriptor readback, - seeded half initialization and device transfer, byte-exact workspace requests, - cleanup, unprepared destruction, strided allocation, and invalid descriptor arrays. -- CLI checks exercise all three convolution directions and controlled failures. - FP16 compute and noncontiguous layouts may report `CUDNN_STATUS_NOT_SUPPORTED`; - those paths must exit nonzero without publishing timings. The FP32-storage/FP32- - compute and FP16-storage/FP32-compute contiguous smoke cases must execute. -- Parser checks preserve names, units, raw output, and the failure marker while - rejecting absent, duplicate, malformed, nonpositive, or non-finite measurements. - They also cover the existing executor's aggregate failure and continuation behavior. -- These are execution and integrity checks, not a full numerical-accuracy test, - performance acceptance, or certification of every default algorithm on every stack. - -For a memory check, run: - -```bash -CUDA_VISIBLE_DEVICES=0 compute-sanitizer --tool memcheck --leak-check full \ - --error-exitcode 99 build/cudnn-tests/cudnn_data_types_test --memcheck -``` - -`--memcheck` skips only the deliberate query of a freed workspace address. The -ordinary test retains that negative check, while sanitizer leak detection checks -that allocations are released. Require zero memory errors and zero leaked bytes. - -The repaired FP16-storage/FP32-compute cases need new baselines. See the -[precision and compatibility note](../../../../docs/user-tutorial/benchmarks/micro-benchmarks.md#precision-and-compatibility). diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h index b6ccc1485..0343255b5 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_config.h @@ -3,7 +3,6 @@ #pragma once -#include #include #include "cudnn_helper.h" @@ -112,7 +111,7 @@ class CudnnConfig { this->e_name = it->second; return e_name; } else { - throw std::invalid_argument("invalid input function name"); + throw "ERROR: invalid input function name"; } } }; diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h index cc13c8e89..f23649f4a 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function.h @@ -18,16 +18,14 @@ namespace cudnn_test { */ template class CudnnFunction : public CudnnConfig { protected: - cudnnHandle_t cudnn_handle = nullptr; + cudnnHandle_t cudnn_handle; TensorDescriptorNd x_desc_; FilterDescriptorNd w_desc_; ConvolutionDescriptor conv_desc_; TensorDescriptorNd h_desc_; - size_t fwd_workspace_size_ = 0; - float *fwd_workspace_ = nullptr; - T1 *x = nullptr; - T1 *filter = nullptr; - T1 *h = nullptr; + size_t fwd_workspace_size_; + float *fwd_workspace_; + T1 *x, *filter, *h; const float alpha_ = 1.f; const float beta_ = 0.f; @@ -66,18 +64,12 @@ template class CudnnFunction : public CudnnConfig { /** * @brief Destroy the Cudnn Function object, including free cuda memory and handle of cudnn and curand */ - virtual ~CudnnFunction() noexcept { + virtual ~CudnnFunction() { // free context and memory - if (x != nullptr) - cudaFree(x); - if (filter != nullptr) - cudaFree(filter); - if (h != nullptr) - cudaFree(h); - if (fwd_workspace_ != nullptr) - cudaFree(fwd_workspace_); - if (cudnn_handle != nullptr) - cudnnDestroy(cudnn_handle); + CUDA_SAFE_CALL(cudaFree(x)); + CUDA_SAFE_CALL(cudaFree(filter)); + CUDA_SAFE_CALL(cudaFree(h)); + cudnn_handle_free(&this->cudnn_handle); } /** * @brief The main procedure for cudnn function test, including warmup, function test and time measurement @@ -104,10 +96,7 @@ template void CudnnFunction::prepare_for_func } // Set convolution algorithm and workspace size this->get_workspace_size(); - if (fwd_workspace_size_ > 0) { - CUDA_SAFE_CALL(cudaMalloc(reinterpret_cast(&fwd_workspace_), fwd_workspace_size_)); - CUDA_SAFE_CALL(cudaMemset(fwd_workspace_, 0, fwd_workspace_size_)); - } + zeros(&fwd_workspace_, std::vector{static_cast(this->fwd_workspace_size_ / sizeof(float)), 1}); } /** * @brief Malloc cuda memory and fill in value for data params used in the cudnn function @@ -116,9 +105,9 @@ template void CudnnFunction::prepare_input() // Allocate memory for filter data rand(&filter, get_filter_dims(), random_seed); // Allocate memory for input data - rand(&x, tensor_storage_size(get_input_dims(), get_input_stride()), random_seed); + rand(&x, get_input_dims(), random_seed); // Allocate memory for output data - rand(&h, tensor_storage_size(get_output_dims(), get_output_stride()), random_seed); + rand(&h, get_output_dims(), random_seed); } /** * @brief The main procedure for cudnn function test, including warmup, function test and time measurement diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h index ab9b5b7b9..d1f93a8bd 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_function_helper.h @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -172,7 +171,7 @@ template CudnnFunction *get_cudnn_function_po case e_cudnnConvolutionBackwardFilter: return new ConvolutionBackwardFilterFunction(function); default: - throw std::invalid_argument("invalid function name"); + throw "invalid function name"; } } @@ -186,24 +185,36 @@ template CudnnFunction *get_cudnn_function_po * @param options the cmd arguments of the application */ void run_benchmark(Options &options) { - json function_config = json::parse(options.para_info_json); - cudnn_test::CudnnConfig function = function_config.get(); - function.set_num_test(options.num_test); - function.set_warm_up(options.warm_up); - function.set_num_in_step(options.num_in_step); - function.set_random_seed(options.random_seed); - function.set_auto_algo(options.auto_algo); - if (function.get_input_type() == CUDNN_DATA_FLOAT && function.get_conv_type() == CUDNN_DATA_FLOAT) { - std::unique_ptr> p_function(get_cudnn_function_pointer(function)); - p_function->benchmark(); - } else if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_FLOAT) { - std::unique_ptr> p_function(get_cudnn_function_pointer(function)); - p_function->benchmark(); - } else if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_HALF) { - std::unique_ptr> p_function(get_cudnn_function_pointer(function)); - p_function->benchmark(); - } else { - throw std::invalid_argument("invalid input and conv type"); + try { + json function_config = json::parse(options.para_info_json); + // convert function params from json to CudnnConfig class + cudnn_test::CudnnConfig function = function_config.get(); + function.set_num_test(options.num_test); + function.set_warm_up(options.warm_up); + function.set_num_in_step(options.num_in_step); + function.set_random_seed(options.random_seed); + function.set_auto_algo(options.auto_algo); + if (function.get_input_type() == CUDNN_DATA_FLOAT && function.get_conv_type() == CUDNN_DATA_FLOAT) { + auto p_function = get_cudnn_function_pointer(function); + p_function->benchmark(); + delete p_function; + } else { + if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_FLOAT) { + auto p_function = get_cudnn_function_pointer(function); + p_function->benchmark(); + delete p_function; + } else { + if (function.get_input_type() == CUDNN_DATA_HALF && function.get_conv_type() == CUDNN_DATA_HALF) { + auto p_function = get_cudnn_function_pointer(function); + p_function->benchmark(); + delete p_function; + } else { + throw "invalid input and conv type"; + } + } + } + } catch (std::exception &e) { + std::cout << "Error: " << e.what() << std::endl; } } } // namespace cudnn_test diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp index 8039c709a..b0e8aa2a5 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.cpp @@ -57,56 +57,31 @@ void cudnn_handle_free(cudnnHandle_t *cudnn_handle) { CHECK_CUDNN_ERROR(cudnnDes * @param random_seed the random seed to generate random data */ template void rand(T **input, std::vector dims_, int random_seed) { - throw std::invalid_argument("unsupported rand data type"); + throw "unsupported rand data type"; } -template <> void rand(float **input, size_t size, int random_seed) { - if (size == 0 || size > std::numeric_limits::max() / sizeof(float)) { - throw std::invalid_argument("invalid float allocation size"); - } +template <> void rand(float **input, std::vector dims_, int random_seed) { + int size = std::accumulate(dims_.begin(), dims_.end(), 1, std::multiplies()); CUDA_SAFE_CALL(cudaMalloc((void **)input, sizeof(float) * size)); float *host_input; CUDA_SAFE_CALL(cudaMallocHost(&host_input, sizeof(float) * size)); - std::unique_ptr host_owner(host_input, cudaFreeHost); srand(random_seed); - for (size_t index = 0; index < size; ++index) { - host_input[index] = (float)std::rand() / (float)(RAND_MAX); + for (int i = 0; i < size; i++) { + host_input[i] = (float)std::rand() / (float)(RAND_MAX); } // copy input data from host to device CUDA_SAFE_CALL(cudaMemcpy(*input, host_input, sizeof(float) * size, cudaMemcpyHostToDevice)); + CUDA_SAFE_CALL(cudaFreeHost(host_input)); } -template <> void rand(half **input, size_t size, int random_seed) { - if (size == 0 || size > std::numeric_limits::max() / sizeof(half)) { - throw std::invalid_argument("invalid half allocation size"); - } +template <> void rand(half **input, std::vector dims_, int random_seed) { + int size = std::accumulate(dims_.begin(), dims_.end(), 1, std::multiplies()); CUDA_SAFE_CALL(cudaMalloc((void **)input, sizeof(half) * size)); half *host_input; CUDA_SAFE_CALL(cudaMallocHost(&host_input, sizeof(half) * size)); - std::unique_ptr host_owner(host_input, cudaFreeHost); srand(random_seed); - for (size_t index = 0; index < size; ++index) { - host_input[index] = __float2half((float)std::rand() / (float)(RAND_MAX)); + for (int i = 0; i < size; i++) { + host_input[i] = __float2half((float)std::rand() / (float)(RAND_MAX)); } CUDA_SAFE_CALL(cudaMemcpy(*input, host_input, sizeof(half) * size, cudaMemcpyHostToDevice)); -} - -size_t contiguous_elements(const std::vector &dims) { - if (dims.empty()) - throw std::invalid_argument("allocation dimensions must not be empty"); - size_t elements = 1; - for (int dimension : dims) { - if (dimension <= 0 || elements > std::numeric_limits::max() / static_cast(dimension)) { - throw std::invalid_argument("invalid or overflowing allocation dimensions"); - } - elements *= static_cast(dimension); - } - return elements; -} - -template <> void rand(float **input, std::vector dims_, int random_seed) { - rand(input, contiguous_elements(dims_), random_seed); -} - -template <> void rand(half **input, std::vector dims_, int random_seed) { - rand(input, contiguous_elements(dims_), random_seed); + CUDA_SAFE_CALL(cudaFreeHost(host_input)); } } // namespace cudnn_test diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h index 3a63f0dcd..7047adbb4 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/cudnn_helper.h @@ -8,11 +8,8 @@ #pragma once #include -#include #include -#include #include -#include #include #include @@ -50,26 +47,6 @@ void cudnn_handle_free(cudnnHandle_t *cudnn_handle); * @param random_seed the random seed to generate random data */ template void rand(T **input, std::vector dims_, int random_seed); -template void rand(T **input, size_t elements, int random_seed); - -inline size_t tensor_storage_size(const std::vector &dims, const std::vector &strides) { - if (dims.empty() || dims.size() != strides.size()) { - throw std::invalid_argument("tensor dimensions and strides must have the same nonzero rank"); - } - size_t elements = 1; - for (size_t axis = 0; axis < dims.size(); ++axis) { - if (dims[axis] <= 0 || strides[axis] <= 0) { - throw std::invalid_argument("tensor dimensions and strides must be positive"); - } - const size_t dimension = static_cast(dims[axis] - 1); - const size_t stride = static_cast(strides[axis]); - if (dimension > (std::numeric_limits::max() - elements) / stride) { - throw std::invalid_argument("tensor storage size overflows size_t"); - } - elements += dimension * stride; - } - return elements; -} /** * @brief Malloc cuda memory and fill in zero * @tparam T @@ -121,9 +98,8 @@ template class TensorDescriptorNd { std::shared_ptr desc_; struct TensorDescriptorNdDeleter { - void operator()(cudnnTensorDescriptor_t *desc) noexcept { - if (*desc != nullptr) - cudnnDestroyTensorDescriptor(*desc); + void operator()(cudnnTensorDescriptor_t *desc) { + CHECK_CUDNN_ERROR(cudnnDestroyTensorDescriptor(*desc)); delete desc; } }; @@ -131,8 +107,7 @@ template class TensorDescriptorNd { public: TensorDescriptorNd() {} TensorDescriptorNd(const std::vector &dim, const std::vector &stride) - : desc_(new cudnnTensorDescriptor_t{}, TensorDescriptorNdDeleter()) { - tensor_storage_size(dim, stride); + : desc_(new cudnnTensorDescriptor_t, TensorDescriptorNdDeleter()) { cudnnDataType_t type; get_tensor_type(type); @@ -151,9 +126,8 @@ template class FilterDescriptorNd { std::shared_ptr desc_; struct FilterDescriptorNdDeleter { - void operator()(cudnnFilterDescriptor_t *desc) noexcept { - if (*desc != nullptr) - cudnnDestroyFilterDescriptor(*desc); + void operator()(cudnnFilterDescriptor_t *desc) { + CHECK_CUDNN_ERROR(cudnnDestroyFilterDescriptor(*desc)); delete desc; } }; @@ -161,10 +135,7 @@ template class FilterDescriptorNd { public: FilterDescriptorNd() {} - FilterDescriptorNd(const std::vector &dim) - : desc_(new cudnnFilterDescriptor_t{}, FilterDescriptorNdDeleter()) { - if (dim.empty()) - throw std::invalid_argument("filter dimensions must not be empty"); + FilterDescriptorNd(const std::vector &dim) : desc_(new cudnnFilterDescriptor_t, FilterDescriptorNdDeleter()) { cudnnTensorFormat_t tensor_format; get_tensor_format(tensor_format); cudnnDataType_t type; @@ -185,9 +156,8 @@ template class ConvolutionDescriptor { std::shared_ptr desc_; struct ConvolutionDescriptorDeleter { - void operator()(cudnnConvolutionDescriptor_t *desc) noexcept { - if (*desc != nullptr) - cudnnDestroyConvolutionDescriptor(*desc); + void operator()(cudnnConvolutionDescriptor_t *desc) { + CHECK_CUDNN_ERROR(cudnnDestroyConvolutionDescriptor(*desc)); delete desc; } }; @@ -196,12 +166,7 @@ template class ConvolutionDescriptor { ConvolutionDescriptor() {} ConvolutionDescriptor(int array_length, const std::vector &padA, const std::vector &filter_strideA, const std::vector &dilationA, cudnnConvolutionMode_t mode) - : desc_(new cudnnConvolutionDescriptor_t{}, ConvolutionDescriptorDeleter()) { - if (array_length <= 0 || padA.size() != static_cast(array_length) || - filter_strideA.size() != static_cast(array_length) || - dilationA.size() != static_cast(array_length)) { - throw std::invalid_argument("convolution dimension arrays have different lengths"); - } + : desc_(new cudnnConvolutionDescriptor_t, ConvolutionDescriptorDeleter()) { cudnnDataType_t type; get_tensor_type(type); diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_binary.py b/tests/benchmarks/micro_benchmarks/test_cudnn_binary.py deleted file mode 100644 index f58bbe3d9..000000000 --- a/tests/benchmarks/micro_benchmarks/test_cudnn_binary.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Run native cuDNN execution checks against SB_CUDNN_TEST_BINARY.""" - -import json -import math -import os -import subprocess -import unittest - - -@unittest.skipUnless( - os.environ.get('SB_CUDNN_TEST_BINARY'), 'Set SB_CUDNN_TEST_BINARY to the compiled native benchmark.' -) -class CudnnBinaryTests(unittest.TestCase): - """Exercise the actual native binary and its controlled error exits.""" - - def configuration(self, name='cudnnConvolutionForward', input_type=0, conv_type=0): - """Create a bounded convolution configuration.""" - return { - 'name': name, - 'algo': 0, - 'inputDims': [1, 2, 3, 3], - 'inputStride': [18, 9, 3, 1], - 'outputDims': [1, 2, 3, 3], - 'outputStride': [18, 9, 3, 1], - 'filterDims': [2, 2, 1, 1], - 'inputType': input_type, - 'convType': conv_type, - 'arrayLength': 2, - 'padA': [0, 0], - 'filterStrideA': [1, 1], - 'dilationA': [1, 1], - 'mode': 1, - 'tensorOp': False, - } - - def run_binary(self, configuration): - """Execute a small case with captured output and a finite deadline.""" - value = json.dumps(configuration) if isinstance(configuration, dict) else configuration - return subprocess.run( - [os.environ['SB_CUDNN_TEST_BINARY'], '--num_test', '2', '--warm_up', '1', '--num_in_step', '1', - '--random_seed', '33931', '--config_json', value], - capture_output=True, text=True, timeout=30 - ) - - def test_convolution_storage_compute_combinations(self): - """Execute supported storage and compute types in all directions.""" - for name in ('cudnnConvolutionForward', 'cudnnConvolutionBackwardData', 'cudnnConvolutionBackwardFilter'): - for input_type, conv_type in ((0, 0), (2, 0)): - with self.subTest(name=name, input_type=input_type, conv_type=conv_type): - result = self.run_binary(self.configuration(name, input_type, conv_type)) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn('Error', result.stdout + result.stderr) - rows = [line for line in result.stdout.splitlines() if line.startswith('[raw_data]:')] - self.assertEqual(len(rows), 1, result.stdout) - samples = [float(value) for value in rows[0].split(':', 1)[1].split(',') if value.strip()] - self.assertEqual(len(samples), 2) - self.assertTrue(all(math.isfinite(value) and value > 0 for value in samples)) - - def test_half_compute_support_or_controlled_rejection(self): - """Keep half-compute capability rejection distinct from an abort.""" - for name in ('cudnnConvolutionForward', 'cudnnConvolutionBackwardData', 'cudnnConvolutionBackwardFilter'): - with self.subTest(name=name): - result = self.run_binary(self.configuration(name, 2, 2)) - if 'CUDNN_STATUS_NOT_SUPPORTED' in result.stdout: - self.assertGreater(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn('[raw_data]:', result.stdout) - else: - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('[raw_data]:', result.stdout) - self.assertNotIn('Error:', result.stdout) - - def test_invalid_json_is_a_controlled_failure(self): - """Reject invalid JSON without timing output.""" - result = self.run_binary('{') - self.assertGreater(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('Error:', result.stdout) - self.assertNotIn('[raw_data]:', result.stdout) - - def test_invalid_type_pair_is_a_controlled_failure(self): - """Reject an unsupported storage and compute type pair.""" - result = self.run_binary(self.configuration(input_type=0, conv_type=2)) - self.assertGreater(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('Error:', result.stdout) - self.assertNotIn('[raw_data]:', result.stdout) - - def test_missing_required_field_is_a_controlled_failure(self): - """Reject an incomplete configuration without a false successful exit.""" - config = self.configuration() - del config['filterDims'] - result = self.run_binary(config) - self.assertGreater(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn('[raw_data]:', result.stdout) - - def test_invalid_function_is_a_controlled_failure(self): - """Reject unknown function names through the normal error handler.""" - result = self.run_binary(self.configuration(name='not-a-cudnn-function')) - self.assertGreater(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('Error:', result.stdout) - self.assertNotIn('[raw_data]:', result.stdout) - - def test_noncontiguous_tensor_strides_execute_or_reject_cleanly(self): - """Respect strided storage when supported and retain capability failures.""" - for name in ('cudnnConvolutionForward', 'cudnnConvolutionBackwardData', 'cudnnConvolutionBackwardFilter'): - with self.subTest(name=name): - config = self.configuration(name) - config['inputStride'] = [40, 20, 5, 1] - config['outputStride'] = [40, 20, 5, 1] - result = self.run_binary(config) - if 'CUDNN_STATUS_NOT_SUPPORTED' in result.stdout: - self.assertGreater(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn('[raw_data]:', result.stdout) - else: - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('[raw_data]:', result.stdout) - - def test_invalid_descriptor_lengths_are_controlled_failures(self): - """Reject incomplete descriptor arrays before unsafe API access.""" - for field, value in (('inputStride', [18]), ('padA', [0]), ('filterDims', [])): - with self.subTest(field=field): - config = self.configuration() - config[field] = value - result = self.run_binary(config) - self.assertGreater(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('Error:', result.stdout) - self.assertNotIn('[raw_data]:', result.stdout) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp b/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp index cfd14fbaa..42d5db90d 100644 --- a/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp +++ b/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp @@ -1,17 +1,13 @@ -#include #include #include #include #include #include -#include #include #include "cudnn_config.h" -#include "cudnn_function.h" using cudnn_test::check_cuda; -using cudnn_test::throw_cudnn_err; void require(bool condition, const char *message) { if (!condition) @@ -37,22 +33,17 @@ void test_half_initialization() { std::srand(seed); for (auto &value : expected) value = __half2float(__float2half(static_cast(std::rand()) / RAND_MAX)); - std::vector first; for (int repeat = 0; repeat < 2; ++repeat) { std::srand(seed + repeat + 1); half *device = nullptr; try { - cudnn_test::rand(&device, {count}, seed); + cudnn_test::rand(&device, std::vector{count}, seed); std::vector host(count); CUDA_SAFE_CALL(cudaMemcpy(host.data(), device, count * sizeof(half), cudaMemcpyDeviceToHost)); std::vector actual(count); for (int index = 0; index < count; ++index) actual[index] = __half2float(host[index]); require(actual == expected, "half data does not match the supplied seed and host-to-device copy"); - if (repeat == 0) - first = actual; - else - require(actual == first, "half initialization depends on ambient RNG state"); CUDA_SAFE_CALL(cudaFree(device)); } catch (...) { if (device != nullptr) @@ -62,143 +53,13 @@ void test_half_initialization() { } } -void test_descriptor_types() { - cudnn_test::TensorDescriptorNd input({1, 2, 3, 3}, {18, 9, 3, 1}); - cudnn_test::FilterDescriptorNd filter({2, 2, 1, 1}); - cudnn_test::ConvolutionDescriptor convolution(2, {0, 0}, {1, 1}, {1, 1}, CUDNN_CROSS_CORRELATION); - cudnnDataType_t storage, filter_type, compute; - cudnnTensorFormat_t format; - cudnnConvolutionMode_t mode; - int rank, dims[4], strides[4], padding[2], dilation[2], conv_stride[2]; - CHECK_CUDNN_ERROR(cudnnGetTensorNdDescriptor(input.desc(), 4, &storage, &rank, dims, strides)); - CHECK_CUDNN_ERROR(cudnnGetFilterNdDescriptor(filter.desc(), 4, &filter_type, &format, &rank, dims)); - CHECK_CUDNN_ERROR( - cudnnGetConvolutionNdDescriptor(convolution.desc(), 2, &rank, padding, conv_stride, dilation, &mode, &compute)); - require(storage == CUDNN_DATA_HALF && filter_type == CUDNN_DATA_HALF && compute == CUDNN_DATA_FLOAT, - "actual cuDNN descriptors do not preserve half storage with float compute"); -} - -cudnn_test::CudnnConfig workspace_config() { - cudnn_test::CudnnConfig config{}; - config.set_input_dims({1, 2, 3, 3}); - config.set_input_stride({18, 9, 3, 1}); - config.set_output_dims({1, 2, 3, 3}); - config.set_output_stride({18, 9, 3, 1}); - config.set_filter_dims({2, 2, 1, 1}); - config.set_array_length(2); - config.set_padA({0, 0}); - config.set_filter_strideA({1, 1}); - config.set_dilationA({1, 1}); - config.set_mode(CUDNN_CROSS_CORRELATION); - config.set_use_tensor_op(false); - config.set_auto_algo(false); - return config; -} - -class WorkspaceProbe : public cudnn_test::CudnnFunction { - size_t requested_bytes_; - - void get_workspace_size() override { fwd_workspace_size_ = requested_bytes_; } - - public: - WorkspaceProbe(cudnn_test::CudnnConfig &config, size_t requested_bytes) - : CudnnFunction(config), requested_bytes_(requested_bytes) { - x = nullptr; - filter = nullptr; - h = nullptr; - } - - void prepare() { prepare_for_function(); } - void prepare_data() { prepare_input(); } - CUdeviceptr input() const { return reinterpret_cast(x); } - CUdeviceptr workspace() const { return reinterpret_cast(fwd_workspace_); } -}; - -void check_workspace_size(size_t bytes) { - auto config = workspace_config(); - WorkspaceProbe function(config, bytes); - function.prepare(); - CUdeviceptr allocation; - size_t allocated_bytes = 0; - require(cuMemGetAddressRange(&allocation, &allocated_bytes, function.workspace()) == CUDA_SUCCESS, - "workspace does not have a valid device allocation"); - require(allocated_bytes >= bytes, "workspace was rounded down below requested bytes"); -} - -void test_workspace_byte_size() { check_workspace_size(13); } -void test_single_byte_workspace() { check_workspace_size(1); } - -void test_workspace_released() { - auto config = workspace_config(); - CUdeviceptr pointer; - { - WorkspaceProbe function(config, 4096); - function.prepare(); - pointer = function.workspace(); - } - CUdeviceptr allocation; - size_t bytes; - require(cuMemGetAddressRange(&allocation, &bytes, pointer) != CUDA_SUCCESS, - "workspace allocation remains live after destruction"); -} - -void test_unprepared_destruction() { - auto config = workspace_config(); - cudnn_test::CudnnFunction function(config); -} - -void test_strided_allocation() { - auto config = workspace_config(); - config.set_input_stride({40, 20, 5, 1}); - config.set_random_seed(33931); - WorkspaceProbe function(config, 0); - function.prepare_data(); - CUdeviceptr allocation; - size_t bytes = 0; - require(cuMemGetAddressRange(&allocation, &bytes, function.input()) == CUDA_SUCCESS, - "strided input allocation is missing"); - require(bytes >= 33 * sizeof(float), "input allocation does not cover the descriptor stride extent"); -} - -void test_invalid_shape_rejected() { - bool rejected = false; - try { - cudnn_test::TensorDescriptorNd descriptor({1, 2, 3, 3}, {18}); - } catch (const std::invalid_argument &) { - rejected = true; - } - require(rejected, "mismatched stride rank was passed to cuDNN"); - rejected = false; - try { - cudnn_test::ConvolutionDescriptor descriptor(2, {0}, {1, 1}, {1, 1}, CUDNN_CROSS_CORRELATION); - } catch (const std::invalid_argument &) { - rejected = true; - } - require(rejected, "mismatched convolution arrays were passed to cuDNN"); -} - -int main(int argc, char **argv) { - const bool memcheck = argc == 2 && std::string(argv[1]) == "--memcheck"; - if (argc > 1 && !memcheck) - return 2; - std::cout.setf(std::ios::unitbuf); +int main() { int failures = 0; const std::vector> tests = { {"independent_types", test_independent_types}, {"half_initialization", test_half_initialization}, - {"descriptor_types", test_descriptor_types}, - {"workspace_byte_size", test_workspace_byte_size}, - {"single_byte_workspace", test_single_byte_workspace}, - {"workspace_released", test_workspace_released}, - {"unprepared_destruction", test_unprepared_destruction}, - {"strided_allocation", test_strided_allocation}, - {"invalid_shape_rejected", test_invalid_shape_rejected}, }; for (const auto &test : tests) { - if (memcheck && std::string(test.first) == "workspace_released") { - std::cout << test.first << ": skipped negative driver query; use sanitizer leak check\n"; - continue; - } try { test.second(); std::cout << test.first << ": passed\n"; diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py b/tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py deleted file mode 100644 index 2358b0a2f..000000000 --- a/tests/benchmarks/micro_benchmarks/test_cudnn_raw_result.py +++ /dev/null @@ -1,180 +0,0 @@ -"""CPU-only tests for cuDNN timing output validation.""" - -import json -import subprocess -import unittest -from types import SimpleNamespace -from unittest.mock import Mock, call, patch - -from superbench.benchmarks import ReturnCode -from superbench.benchmarks.micro_benchmarks.cudnn_function import CudnnBenchmark - - -class CudnnRawResultTests(unittest.TestCase): - """Test parsing without preprocessing or launching the native benchmark.""" - - def setUp(self): - """Provide only the state consumed by the timing parser.""" - self.benchmark = CudnnBenchmark.__new__(CudnnBenchmark) - self.benchmark._name = 'cudnn-function' - self.benchmark._curr_run_index = 0 - self.benchmark._args = SimpleNamespace(num_steps=3, log_raw_data=False) - self.benchmark._result = Mock(spec=['add_raw_data', 'add_result']) - configuration = { - 'tensorOp': True, - 'name': 'cudnnConvolutionForward', - 'inputDims': [1, 2, 3, 3], - 'algo': 1, - } - self.benchmark._commands = ["cudnn_benchmark --config_json '{}'".format(json.dumps(configuration))] - self.metric = 'name_cudnnconvolutionforward_algo_1_inputdims_[1_2_3_3]_tensorop_true_time' - self.valid_row = '[raw_data]: 0.001,0.002,0.003,' - - def assert_valid_output(self, raw_output, samples, mean_time): - """Check successful metrics, units, and unmodified raw output.""" - self.benchmark._result.reset_mock() - self.assertIs(self.benchmark._process_raw_result(0, raw_output), True) - self.benchmark._result.add_result.assert_called_once_with(self.metric, mean_time) - self.assertEqual( - self.benchmark._result.add_raw_data.call_args_list, - [ - call('raw_output_0', raw_output, self.benchmark._args.log_raw_data), - call(self.metric, samples, self.benchmark._args.log_raw_data), - ] - ) - - def assert_invalid_output(self, raw_output): - """Require failure without any partial timing data or good metric.""" - self.benchmark._result.reset_mock() - self.assertIs(self.benchmark._process_raw_result(0, raw_output), False) - self.benchmark._result.add_result.assert_called_once_with(self.metric, -1) - self.benchmark._result.add_raw_data.assert_called_once_with( - 'raw_output_0', raw_output, self.benchmark._args.log_raw_data - ) - - def test_valid_native_output(self): - """Keep naming, milliseconds-to-microseconds scaling, and logging flags.""" - raw_output = 'cuDNN benchmark\n{}\nBenchmark completed\n'.format(self.valid_row) - for log_raw_data in (False, True): - with self.subTest(log_raw_data=log_raw_data): - self.benchmark._args.log_raw_data = log_raw_data - self.assert_valid_output(raw_output, [0.001, 0.002, 0.003], 2.0) - - def test_valid_without_trailing_comma(self): - """Do not drop the last sample when the optional comma is absent.""" - self.assert_valid_output('[raw_data]: 0.001,0.002,0.003', [0.001, 0.002, 0.003], 2.0) - - def test_valid_with_whitespace(self): - """Allow whitespace around the native values and trailing comma.""" - self.assert_valid_output('[raw_data]: \t1e-3, 2e-3, 3e-3, \t\n', [0.001, 0.002, 0.003], 2.0) - - def test_absent_timing_record(self): - """Empty or informational output cannot report success.""" - for raw_output in ('', '\n \n', 'cuDNN benchmark completed\n'): - with self.subTest(raw_output=raw_output): - self.assert_invalid_output(raw_output) - - def test_empty_timing_record(self): - """A timing marker alone is not a measurement.""" - for raw_output in ('[raw_data]:', '[raw_data]: \n', '[raw_data]: ,', '[raw_data]: \t, \t'): - with self.subTest(raw_output=raw_output): - self.assert_invalid_output(raw_output) - - def test_non_finite_samples(self): - """Reject NaN, infinity, and numbers that overflow float parsing.""" - for sample in ('nan', 'NaN', 'inf', '-inf', '+Inf', '1e309', '-1e309'): - with self.subTest(sample=sample): - self.assert_invalid_output('[raw_data]: 0.001,{},0.003,'.format(sample)) - - def test_non_positive_samples(self): - """Every sample must be positive, including after float underflow.""" - for sample in ('0', '0.0', '-0.0', '-0.001', '1e-400'): - with self.subTest(sample=sample): - self.assert_invalid_output('[raw_data]: 0.001,{},0.003,'.format(sample)) - - def test_wrong_sample_count(self): - """Require exactly num_steps samples, with or without a final comma.""" - for samples in ('0.001,', '0.001,0.002,', '0.001,0.002,0.003,0.004,', '0.001,0.002,0.003,0.004'): - with self.subTest(samples=samples): - self.assert_invalid_output('[raw_data]: ' + samples) - - def test_non_positive_num_steps(self): - """Zero or negative requested steps cannot produce a valid record.""" - for num_steps in (0, -1): - for raw_output in ('[raw_data]: ', self.valid_row): - with self.subTest(num_steps=num_steps, raw_output=raw_output): - self.benchmark._args.num_steps = num_steps - self.assert_invalid_output(raw_output) - - def test_duplicate_timing_records(self): - """Reject a second record without retaining the first measurement.""" - for second_row in (self.valid_row, '[raw_data]: 0.004,0.005,0.006,', '[raw_data]: '): - with self.subTest(second_row=second_row): - self.assert_invalid_output(self.valid_row + '\n' + second_row) - - def test_malformed_timing_record(self): - """Do not discard invalid tokens or extra delimiters as a final comma.""" - for raw_output in ( - '[raw_data] 0.001,0.002,0.003,', - '[raw_data]: 0.001,invalid,0.003,', - '[raw_data]: 0.001,,0.003,', - '[raw_data]: ,0.001,0.002,0.003,', - '[raw_data]: 0.001,0.002,0.003,,', - '[raw_data]: 0.001,0.002,0.003, ,', - '[raw_data]: 0.001,0.002,0.003,garbage', - ): - with self.subTest(raw_output=raw_output): - self.assert_invalid_output(raw_output) - - def test_error_before_or_after_valid_record(self): - """An error anywhere in stdout invalidates otherwise valid timings.""" - for raw_output in ( - 'Error: CUDNN_STATUS_NOT_SUPPORTED\n' + self.valid_row, - self.valid_row + '\nError: cuDNN call failed', - ): - with self.subTest(raw_output=raw_output): - self.assert_invalid_output(raw_output) - - def test_error_without_timing_record(self): - """Keep the existing failure marker when only an error is reported.""" - self.assert_invalid_output('Error: CUDNN_STATUS_NOT_SUPPORTED\n') - - def test_unit_conversion_overflow(self): - """Finite input samples must not produce an infinite scaled metric.""" - self.assert_invalid_output('[raw_data]: 1e306,1e306,1e306,') - - def test_large_finite_scaled_metric(self): - """Do not reject large timings whose scaled mean remains finite.""" - self.assert_valid_output('[raw_data]: 1e300,1e300,1e300,', [1e300, 1e300, 1e300], 1e300 * 1000) - - def test_tolerant_invoke_keeps_failure_and_later_successful_cases(self): - """A native rejection must not erase valid timings or become overall success.""" - self.benchmark._args.tolerant_fail = True - self.benchmark._args.log_flushing = False - self.benchmark._args.bin_dir = '/tmp' - self.benchmark._result = Mock(spec=['add_raw_data', 'add_result', 'set_return_code']) - self.benchmark._commands *= 3 - outcomes = [subprocess.CompletedProcess('binary', 0, self.valid_row), - subprocess.CompletedProcess('binary', 255, 'Error: CUDNN_STATUS_NOT_SUPPORTED'), - subprocess.CompletedProcess('binary', 0, self.valid_row)] - with patch('superbench.benchmarks.micro_benchmarks.micro_base.run_command', side_effect=outcomes) as execute: - self.assertFalse(self.benchmark._benchmark()) - self.assertEqual(execute.call_count, 3) - self.benchmark._result.set_return_code.assert_called_once_with(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE) - self.assertEqual(self.benchmark._result.add_result.call_args_list, [call(self.metric, 2.0)] * 2) - - def test_zero_exit_empty_output_sets_parsing_failure(self): - """An empty successful process is not a successful benchmark measurement.""" - self.benchmark._args.tolerant_fail = True - self.benchmark._args.log_flushing = False - self.benchmark._args.bin_dir = '/tmp' - self.benchmark._result = Mock(spec=['add_raw_data', 'add_result', 'set_return_code']) - with patch('superbench.benchmarks.micro_benchmarks.micro_base.run_command', - return_value=subprocess.CompletedProcess('binary', 0, '')): - self.assertFalse(self.benchmark._benchmark()) - self.benchmark._result.set_return_code.assert_called_once_with(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - self.benchmark._result.add_result.assert_called_once_with(self.metric, -1) - - -if __name__ == '__main__': - unittest.main() From bb7391a9e6796604f0e250e1ef38d84595b31e17 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 10 Sep 2026 23:58:11 +0000 Subject: [PATCH 3/3] Benchmarks: Keep cuDNN precision fix runtime-only --- .../cudnn_function/CMakeLists.txt | 9 --- .../test_cudnn_data_types.cpp | 72 ------------------- 2 files changed, 81 deletions(-) delete mode 100644 tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp diff --git a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt index 902569257..00ab0e470 100644 --- a/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt +++ b/superbench/benchmarks/micro_benchmarks/cudnn_function/CMakeLists.txt @@ -30,14 +30,5 @@ 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_DATA_TYPES_TEST_SOURCE - ${CMAKE_CURRENT_SOURCE_DIR}/../../../../tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp) - if(EXISTS "${CUDNN_DATA_TYPES_TEST_SOURCE}") - add_executable(cudnn_data_types_test EXCLUDE_FROM_ALL ${CUDNN_DATA_TYPES_TEST_SOURCE}) - target_include_directories(cudnn_data_types_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) - target_link_libraries(cudnn_data_types_test ${TARGET_NAME} CUDA::cudart ${CUDNN_LIBRARY}) - endif() - install(TARGETS cudnn_benchmark ${TARGET_NAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib) endif() diff --git a/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp b/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp deleted file mode 100644 index 42d5db90d..000000000 --- a/tests/benchmarks/micro_benchmarks/test_cudnn_data_types.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "cudnn_config.h" - -using cudnn_test::check_cuda; - -void require(bool condition, const char *message) { - if (!condition) - throw std::runtime_error(message); -} - -void test_independent_types() { - cudnn_test::CudnnConfig config{}; - config.set_input_type(CUDNN_DATA_HALF); - config.set_conv_type(CUDNN_DATA_FLOAT); - require(config.get_input_type() == CUDNN_DATA_HALF, "compute type overwrote half storage type"); - require(config.get_conv_type() == CUDNN_DATA_FLOAT, "compute type was not stored independently"); - config.set_conv_type(CUDNN_DATA_HALF); - config.set_input_type(CUDNN_DATA_FLOAT); - require(config.get_conv_type() == CUDNN_DATA_HALF, "storage type overwrote compute type"); - require(config.get_input_type() == CUDNN_DATA_FLOAT, "storage type did not change"); -} - -void test_half_initialization() { - constexpr int count = 257; - constexpr int seed = 33931; - std::vector expected(count); - std::srand(seed); - for (auto &value : expected) - value = __half2float(__float2half(static_cast(std::rand()) / RAND_MAX)); - for (int repeat = 0; repeat < 2; ++repeat) { - std::srand(seed + repeat + 1); - half *device = nullptr; - try { - cudnn_test::rand(&device, std::vector{count}, seed); - std::vector host(count); - CUDA_SAFE_CALL(cudaMemcpy(host.data(), device, count * sizeof(half), cudaMemcpyDeviceToHost)); - std::vector actual(count); - for (int index = 0; index < count; ++index) - actual[index] = __half2float(host[index]); - require(actual == expected, "half data does not match the supplied seed and host-to-device copy"); - CUDA_SAFE_CALL(cudaFree(device)); - } catch (...) { - if (device != nullptr) - cudaFree(device); - throw; - } - } -} - -int main() { - int failures = 0; - const std::vector> tests = { - {"independent_types", test_independent_types}, - {"half_initialization", test_half_initialization}, - }; - for (const auto &test : tests) { - try { - test.second(); - std::cout << test.first << ": passed\n"; - } catch (const std::exception &error) { - ++failures; - std::cout << test.first << ": failed: " << error.what() << '\n'; - } - } - return failures == 0 ? 0 : 1; -} \ No newline at end of file