From f9d99f3f8e6e3d9436499a89dc5169d5cc4c18fa Mon Sep 17 00:00:00 2001 From: Rahul Garg Date: Thu, 13 Feb 2020 23:21:40 -0800 Subject: [PATCH 1/2] [sample] Add hipDispatchEnqueueRateMT (#1869) * [sample] Add hipDispatchEnqueueRateMT --- samples/1_Utils/hipDispatchLatency/Makefile | 11 +- .../hipDispatchEnqueueRateMT.cpp | 167 ++++++++++++++++++ 2 files changed, 173 insertions(+), 5 deletions(-) create mode 100644 samples/1_Utils/hipDispatchLatency/hipDispatchEnqueueRateMT.cpp diff --git a/samples/1_Utils/hipDispatchLatency/Makefile b/samples/1_Utils/hipDispatchLatency/Makefile index 0616f01f0d..74945dc515 100644 --- a/samples/1_Utils/hipDispatchLatency/Makefile +++ b/samples/1_Utils/hipDispatchLatency/Makefile @@ -4,16 +4,17 @@ ifeq (,$(HIP_PATH)) endif HIPCC=$(HIP_PATH)/bin/hipcc -std=c++11 -EXE=hipDispatchLatency - CXXFLAGS = -O3 -all: test_kernel.code ${EXE} +all: test_kernel.code hipDispatchLatency.out hipDispatchEnqueueRateMT.out -$(EXE): hipDispatchLatency.cpp +hipDispatchLatency.out: hipDispatchLatency.cpp $(HIPCC) $(CXXFLAGS) hipDispatchLatency.cpp -o $@ +hipDispatchEnqueueRateMT.out: hipDispatchEnqueueRateMT.cpp + $(HIPCC) $(CXXFLAGS) hipDispatchEnqueueRateMT.cpp -o $@ + test_kernel.code: test_kernel.cpp $(HIP_PATH)/bin/hipcc --genco $(GENCO_FLAGS) $^ -o $@ clean: - rm -f *.o $(EXE) + rm -f *.o *.out diff --git a/samples/1_Utils/hipDispatchLatency/hipDispatchEnqueueRateMT.cpp b/samples/1_Utils/hipDispatchLatency/hipDispatchEnqueueRateMT.cpp new file mode 100644 index 0000000000..d1b5c2f3b5 --- /dev/null +++ b/samples/1_Utils/hipDispatchLatency/hipDispatchEnqueueRateMT.cpp @@ -0,0 +1,167 @@ +/* +Copyright (c) 2020-present Advanced Micro Devices, Inc. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +#include +#include "hip/hip_runtime.h" +#ifdef __HIP_PLATFORM_HCC__ +#include "hip/hip_ext.h" +#endif +#include +#include +#include +#include +#include +#include +#include + +#define NUM_GROUPS 1 +#define GROUP_SIZE 1 +#define WARMUP_RUN_COUNT 10 +#define TIMING_RUN_COUNT 100 +#define TOTAL_RUN_COUNT WARMUP_RUN_COUNT + TIMING_RUN_COUNT + +__global__ void EmptyKernel() {} + +// Helper to print various timing metrics +void print_timing(std::string test, std::array &results, int batch = 1) +{ + + float total_us = 0.0f, mean_us = 0.0f, stddev_us = 0.0f; + + // remove top outliers due to nature of variability across large number of multi-threaded runs + std::sort(results.begin(), results.end(), std::greater()); + auto start_iter = std::next(results.begin(), WARMUP_RUN_COUNT); + auto end_iter = results.end(); + + // mean + std::for_each(start_iter, end_iter, [&](const float &run_ms) { + total_us += (run_ms * 1000) / batch; + }); + mean_us = total_us / TIMING_RUN_COUNT; + + // stddev + total_us = 0; + std::for_each(start_iter, end_iter, [&](const float &run_ms) { + float dev_us = ((run_ms * 1000) / batch) - mean_us; + total_us += dev_us * dev_us; + }); + stddev_us = sqrt(total_us / TIMING_RUN_COUNT); + + printf("\n %s: %.1f us, std: %.1f us\n", test.c_str(), mean_us, stddev_us); +} + +// Measure time taken to enqueue a kernel on the GPU using hipModuleLaunchKernel +void hipModuleLaunchKernel_enqueue_rate(std::atomic_int* shared, int max_threads) +{ + //resources necessary for this thread + hipStream_t stream; + hipStreamCreate(&stream); + hipModule_t module; + hipFunction_t function; + hipModuleLoad(&module, "test_kernel.code"); + hipModuleGetFunction(&function, module, "test"); + void* kernel_params = nullptr; + std::array results; + + //synchronize all threads, before running + int tid = shared->fetch_add(1, std::memory_order_release); + while (max_threads != shared->load(std::memory_order_acquire)) {} + + for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { + auto start = std::chrono::high_resolution_clock::now(); + hipModuleLaunchKernel(function, 1, 1, 1, 1, 1, 1, 0, stream, &kernel_params, nullptr); + auto stop = std::chrono::high_resolution_clock::now(); + results[i] = std::chrono::duration(stop - start).count(); + } + print_timing("Thread ID : " + std::to_string(tid) + " , " + "hipModuleLaunchKernel enqueue rate", results); +} + +// Measure time taken to enqueue a kernel on the GPU using hipLaunchKernelGGL +void hipLaunchKernelGGL_enqueue_rate(std::atomic_int* shared, int max_threads) +{ + //resources necessary for this thread + hipStream_t stream; + hipStreamCreate(&stream); + std::array results; + + //synchronize all threads, before running + int tid = shared->fetch_add(1, std::memory_order_release); + while (max_threads != shared->load(std::memory_order_acquire)) {} + + for (auto i = 0; i < TOTAL_RUN_COUNT; ++i) { + auto start = std::chrono::high_resolution_clock::now(); + hipLaunchKernelGGL((EmptyKernel), dim3(NUM_GROUPS), dim3(GROUP_SIZE), 0, stream); + auto stop = std::chrono::high_resolution_clock::now(); + results[i] = std::chrono::duration(stop - start).count(); + } + print_timing("Thread ID : " + std::to_string(tid) + " , " + "hipLaunchKernelGGL enqueue rate", results); +} + +// Simple thread pool +struct thread_pool { + thread_pool(int total_threads) : max_threads(total_threads) {} + void start(std::function f) { + for (int i = 0; i < max_threads; ++i) { + threads.push_back(std::async(std::launch::async, f, &shared, max_threads)); + } + } + void finish() { + for (auto&&thread : threads) { + thread.get(); + } + threads.clear(); + shared = {0}; + } + ~thread_pool() { + finish(); + } +private: + std::atomic_int shared {0}; + std::vector> threads; + int max_threads = 1; +}; + + +int main(int argc, char* argv[]) +{ + if (argc != 3) { + std::cerr << "Run test as 'hipDispatchEnqueueRateMT <0-hipModuleLaunchKernel /1-hipLaunchKernelGGL>'\n"; + return -1; + } + + int max_threads = atoi(argv[1]); + int run_module_test = atoi(argv[2]); + if(max_threads < 1 || run_module_test < 0 || run_module_test > 1) { + std::cerr << "Invalid Input.\n"; + std::cerr << "Run test as 'hipDispatchEnqueueRateMT <0-hipModuleLaunchKernel /1-hipLaunchKernelGGL>'\n"; + return -1; + } + thread_pool task(max_threads); + + if(run_module_test == 0) { + task.start(hipModuleLaunchKernel_enqueue_rate); + task.finish(); + } else { + task.start(hipLaunchKernelGGL_enqueue_rate); + task.finish(); + } + + return 0; +} + From 409b21017c529cc5bc63152fe4988f25866d22ab Mon Sep 17 00:00:00 2001 From: Rahul Garg Date: Fri, 28 Feb 2020 03:17:15 -0800 Subject: [PATCH 2/2] Remove deprecated HIP markers (#1876) --- samples/2_Cookbook/2_Profiler/Makefile | 53 ----- .../2_Cookbook/2_Profiler/MatrixTranspose.cpp | 219 ------------------ samples/2_Cookbook/2_Profiler/Readme.md | 47 ---- 3 files changed, 319 deletions(-) delete mode 100644 samples/2_Cookbook/2_Profiler/Makefile delete mode 100644 samples/2_Cookbook/2_Profiler/MatrixTranspose.cpp delete mode 100644 samples/2_Cookbook/2_Profiler/Readme.md diff --git a/samples/2_Cookbook/2_Profiler/Makefile b/samples/2_Cookbook/2_Profiler/Makefile deleted file mode 100644 index db2d008182..0000000000 --- a/samples/2_Cookbook/2_Profiler/Makefile +++ /dev/null @@ -1,53 +0,0 @@ -HIP_PATH?= $(wildcard /opt/rocm/hip) - -HIPCC=$(HIP_PATH)/bin/hipcc - - -HIPPROFILER=/opt/rocm/bin/rocm-profiler -PROFILER_OPT=-A -o MT.atp -e HIP_PROFILE_API=1 -HIPPROFILER_POST_CMD=$(HIP_PATH)/bin/hipdemangleatp MT.atp - -TARGET=hcc - -SOURCES = MatrixTranspose.cpp -OBJECTS = $(SOURCES:.cpp=.o) - -EXECUTABLE=./MatrixTranspose - -.PHONY: test - - -all: $(EXECUTABLE) profile - - - -OPT =-g -CXXFLAGS =$(OPT) -CXX=$(HIPCC) - - -$(EXECUTABLE): $(OBJECTS) - $(HIPCC) $(OBJECTS) -o $@ - - -profile: $(EXECUTABLE) - $(HIPPROFILER) $(PROFILER_OPT) $(EXECUTABLE) - $(HIPPROFILER_POST_CMD) - - -# Pass option to control start and stop iterations for profiling - see MatrixTranspose.cpp for implementation: -# Note we start profiler in --startdisabled mode - no timing collected until app enabled it via hipProfilerStart() -profile_trigger: $(EXECUTABLE) - $(HIPPROFILER) $(PROFILER_OPT) --startdisabled $(EXECUTABLE) 3 6 - $(HIPPROFILER_POST_CMD) - - -run: $(EXECUTABLE) - $(EXECUTABLE) - - -clean: - rm -f $(EXECUTABLE) - rm -f $(OBJECTS) - rm -f $(HIP_PATH)/src/*.o - diff --git a/samples/2_Cookbook/2_Profiler/MatrixTranspose.cpp b/samples/2_Cookbook/2_Profiler/MatrixTranspose.cpp deleted file mode 100644 index 69266e1288..0000000000 --- a/samples/2_Cookbook/2_Profiler/MatrixTranspose.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* -Copyright (c) 2015-present Advanced Micro Devices, Inc. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -#include - -// hip header file -#include "hip/hip_runtime.h" -#include "hip/hip_profile.h" - -#define WIDTH 1024 - -#define NUM (WIDTH * WIDTH) - -#define THREADS_PER_BLOCK_X 4 -#define THREADS_PER_BLOCK_Y 4 -#define THREADS_PER_BLOCK_Z 1 - -#define ITERATIONS 10 - -// Cmdline parms to control start and stop triggers -int startTriggerIteration = -1; -int stopTriggerIteration = -1; - -// Device (Kernel) function, it must be void -__global__ void matrixTranspose(float* out, float* in, const int width) { - int x = hipBlockDim_x * hipBlockIdx_x + hipThreadIdx_x; - int y = hipBlockDim_y * hipBlockIdx_y + hipThreadIdx_y; - - out[y * width + x] = in[x * width + y]; -} - -// CPU implementation of matrix transpose -void matrixTransposeCPUReference(float* output, float* input, const unsigned int width) { - for (unsigned int j = 0; j < width; j++) { - for (unsigned int i = 0; i < width; i++) { - output[i * width + j] = input[j * width + i]; - } - } -} - - -// Use a separate function to demonstrate how to use function name as part of scoped marker: -void runGPU(float* Matrix, float* TransposeMatrix, float* gpuMatrix, float* gpuTransposeMatrix) { - // __func__ is a standard C++ macro which expands to the name of the function, in this case - // "runGPU" - HIP_SCOPED_MARKER(__func__, "MyGroup"); - - for (int i = 0; i < ITERATIONS; i++) { - if (i == startTriggerIteration) { - hipProfilerStart(); - } - if (i == stopTriggerIteration) { - hipProfilerStop(); - } - - float eventMs = 0.0f; - - hipEvent_t start, stop; - hipEventCreate(&start); - hipEventCreate(&stop); - - - // Record the start event - hipEventRecord(start, NULL); - - // Memory transfer from host to device - hipMemcpy(gpuMatrix, Matrix, NUM * sizeof(float), hipMemcpyHostToDevice); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("hipMemcpyHostToDevice time taken = %6.3fms\n", eventMs); - - // Record the start event - hipEventRecord(start, NULL); - - // Lauching kernel from host - hipLaunchKernelGGL(matrixTranspose, - dim3(WIDTH / THREADS_PER_BLOCK_X, WIDTH / THREADS_PER_BLOCK_Y), - dim3(THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y), 0, 0, gpuTransposeMatrix, - gpuMatrix, WIDTH); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - hipEventElapsedTime(&eventMs, start, stop); - - printf("kernel Execution time = %6.3fms\n", eventMs); - - // Record the start event - hipEventRecord(start, NULL); - - // Memory transfer from device to host - hipMemcpy(TransposeMatrix, gpuTransposeMatrix, NUM * sizeof(float), hipMemcpyDeviceToHost); - - // Record the stop event - hipEventRecord(stop, NULL); - hipEventSynchronize(stop); - - hipEventElapsedTime(&eventMs, start, stop); - - printf("hipMemcpyDeviceToHost time taken = %6.3fms\n", eventMs); - } -}; - - -int main(int argc, char* argv[]) { - if (argc >= 2) { - startTriggerIteration = atoi(argv[1]); - printf("info : will start tracing at iteration:%d\n", startTriggerIteration); - } - if (argc >= 3) { - stopTriggerIteration = atoi(argv[2]); - printf("info : will stop tracing at iteration:%d\n", stopTriggerIteration); - } - - float* Matrix; - float* TransposeMatrix; - float* cpuTransposeMatrix; - - float* gpuMatrix; - float* gpuTransposeMatrix; - - hipDeviceProp_t devProp; - hipGetDeviceProperties(&devProp, 0); - - std::cout << "Device name " << devProp.name << std::endl; - - { - // Show example of how to create a "scoped marker". - // The scoped marker records the time spent inside the { scope } of the marker - the begin - // timestamp is at the beginning of the code scope, and the end is recorded when the SCOPE - // exits. This can be viewed in CodeXL timeline relative to other GPU and CPU events. This - // marker captures the time spent in setup including host allocation, initialization, and - // device memory allocation. - HIP_SCOPED_MARKER("Setup", "MyGroup"); - - - Matrix = (float*)malloc(NUM * sizeof(float)); - TransposeMatrix = (float*)malloc(NUM * sizeof(float)); - cpuTransposeMatrix = (float*)malloc(NUM * sizeof(float)); - - // initialize the input data - for (int i = 0; i < NUM; i++) { - Matrix[i] = (float)i * 10.0f; - } - - - // allocate the memory on the device side - hipMalloc((void**)&gpuMatrix, NUM * sizeof(float)); - hipMalloc((void**)&gpuTransposeMatrix, NUM * sizeof(float)); - - // FYI, the scoped-marker will be destroyed here when the scope exits, and will record its - // "end" timestamp. - } - - runGPU(Matrix, TransposeMatrix, gpuMatrix, gpuTransposeMatrix); - - - // show how to use explicit begin/end markers: - // We begin the timed region with HIP_BEGIN_MARKER, passing in the markerName and group: - // The region will stop when HIP_END_MARKER is called - // This is another way to mark begin/end - as an alternative to scoped markers. - HIP_BEGIN_MARKER("Check&TearDown", "MyGroup"); - - int errors = 0; - - // CPU MatrixTranspose computation - matrixTransposeCPUReference(cpuTransposeMatrix, Matrix, WIDTH); - - // verify the results - double eps = 1.0E-6; - for (int i = 0; i < NUM; i++) { - if (std::abs(TransposeMatrix[i] - cpuTransposeMatrix[i]) > eps) { - errors++; - } - } - if (errors != 0) { - printf("FAILED: %d errors\n", errors); - } else { - printf("PASSED!\n"); - } - - // free the resources on device side - hipFree(gpuMatrix); - hipFree(gpuTransposeMatrix); - - // free the resources on host side - free(Matrix); - free(TransposeMatrix); - free(cpuTransposeMatrix); - - // This ends the last marker started in this thread, in this case "Check&TearDown" - HIP_END_MARKER(); - - return errors; -} diff --git a/samples/2_Cookbook/2_Profiler/Readme.md b/samples/2_Cookbook/2_Profiler/Readme.md deleted file mode 100644 index 8b32beb348..0000000000 --- a/samples/2_Cookbook/2_Profiler/Readme.md +++ /dev/null @@ -1,47 +0,0 @@ -## Using hipEvents to measure performance ### - -This tutorial is follow-up of the previous two tutorial where we learn how to write our first hip program, in which we compute Matrix Transpose and in second one, we added feature to measure time taken for memory transfer and kernel execution. In this tutorial, we'll explain how to use the codexl/rocm-profiler for hip timeline tracing. Also, we will augment the source code with additional markers so we can see the high-level application flow alongside the information that CodeXL automatically collects. - - -## Introduction: - -CodeXL and rocm-profiler are the tool used for profiling the application, which is of prominent use in optimizing the application by means of finding the memory bottlenecks and etc. - -## Requirement: -[CodeXL Installation](http://gpuopen.com/compute-product/codexl/) - -## prerequiste knowledge: - -Programmers familiar with CUDA, OpenCL will be able to quickly learn and start coding with the HIP API. In case you are not, don't worry. You choose to start with the best one. We'll be explaining everything assuming you are completely new to gpgpu programming. - -## Simple Matrix Transpose - -We will be using the Simple Matrix Transpose source code from the previous tutorial as it is. - -## Using CodeXL markers for HIP Functions - -HIP can generate markers at function being/end which are displayed on the CodeXL timeline view. To do this, you need to install ROCm-Profiler and enable HIP to generate the markers: - -1. Install ROCm-Profiler Installing HIP from the rocm pre-built packages, installs the ROCm-Profiler as well. Alternatively, you can build ROCm-Profiler using the instructions given below. - - -2. Run with profiler enabled to generate ATP file. -(These steps are also captured in the Makefile) -The HIP_PROFILE_API enables display of the HIP APIs on the CodeXL trimeline view. -`/opt/rocm/bin/rocm-profiler -o -A -e HIP_PROFILE_API=1 ` - -##Using HIP_TRACE_API - -You can also print the HIP function strings to stderr using HIP_TRACE_API environment variable. This can also be combined with the more detailed debug information provided by the HIP_DB switch. For example: -`HIP_TRACE_API=1 HIP_DB=0x2 ./myHipApp` -Note this trace mode uses colors. "less -r" can handle raw control characters and will display the debug output in proper colors. - -## More Info: -- [HIP FAQ](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_faq.md) -- [HIP Kernel Language](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md) -- [HIP Runtime API (Doxygen)](http://rocm-developer-tools.github.io/HIP) -- [HIP Porting Guide](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_porting_guide.md) -- [HIP Terminology](https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_terms.md) (including Rosetta Stone of GPU computing terms across CUDA/HIP/HC/AMP/OpenL) -- [HIPIFY](https://github.com/ROCm-Developer-Tools/HIP/blob/master/hipify-clang/README.md) -- [Developer/CONTRIBUTING Info](https://github.com/ROCm-Developer-Tools/HIP/blob/master/CONTRIBUTING.md) -- [Release Notes](https://github.com/ROCm-Developer-Tools/HIP/blob/master/RELEASE.md)