From 501160d26239ef3b45e15200bb855a393ec32809 Mon Sep 17 00:00:00 2001 From: irvingzhang0512 Date: Fri, 23 Apr 2021 14:57:01 +0800 Subject: [PATCH] Support TSM-R50 C++ API (#500) * C++ API for TSM-R50 * fix bugs --- tsm/CMakeLists.txt | 25 +++ tsm/README.md | 21 +- tsm/demo.sh | 28 ++- tsm/logging.h | 503 +++++++++++++++++++++++++++++++++++++++++++++ tsm/tsm_r50.cpp | 422 +++++++++++++++++++++++++++++++++++++ tsm/tsm_r50.py | 35 +++- 6 files changed, 1020 insertions(+), 14 deletions(-) create mode 100644 tsm/CMakeLists.txt create mode 100644 tsm/logging.h create mode 100644 tsm/tsm_r50.cpp diff --git a/tsm/CMakeLists.txt b/tsm/CMakeLists.txt new file mode 100644 index 0000000..0332e63 --- /dev/null +++ b/tsm/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 2.6) + +project(TSM) + +add_definitions(-std=c++11) + +option(CUDA_USE_STATIC_CUDA_RUNTIME OFF) +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_BUILD_TYPE Debug) + +include_directories(${PROJECT_SOURCE_DIR}/include) +# include and link dirs of cuda and tensorrt, you need adapt them if yours are different +# cuda +include_directories(/usr/local/cuda/include) +link_directories(/usr/local/cuda/lib64) + +# tensorrt +include_directories(/home/ubuntu/TensorRT/include/) +link_directories(/home/ubuntu/TensorRT/lib/) + +add_executable(tsm_r50 ${PROJECT_SOURCE_DIR}/tsm_r50.cpp) +target_link_libraries(tsm_r50 nvinfer) +target_link_libraries(tsm_r50 cudart) + +add_definitions(-O2 -pthread) diff --git a/tsm/README.md b/tsm/README.md index d10e506..e3081df 100644 --- a/tsm/README.md +++ b/tsm/README.md @@ -23,9 +23,12 @@ More details about the shift module(which is the core of TSM) could to [test_shi python gen_wts.py /path/to/pytorch.pth --out-filename /path/to/tensorrt.wts ``` -+ Step 3: Modify configs in `tsm_r50.py`. ++ Step 3: Test Python API. + + Modify configs in `tsm_r50.py`. + + Inference with `tsm_r50.py`. ```python +# Supported settings BATCH_SIZE = 1 NUM_SEGMENTS = 8 INPUT_H = 224 @@ -34,10 +37,8 @@ OUTPUT_SIZE = 400 SHIFT_DIV = 8 ``` -+ Step 4: Inference with `tsm_r50.py`. - ```shell -usage: tsm_r50.py [-h] [--tensorrt-weights TENSORRT_WEIGHTS] [--input-video INPUT_VIDEO] [--save-engine-path SAVE_ENGINE_PATH] [--load-engine-path LOAD_ENGINE_PATH] [--test-mmaction2] [--mmaction2-config MMACTION2_CONFIG] [--mmaction2-checkpoint MMACTION2_CHECKPOINT] +usage: tsm_r50.py [-h] [--tensorrt-weights TENSORRT_WEIGHTS] [--input-video INPUT_VIDEO] [--save-engine-path SAVE_ENGINE_PATH] [--load-engine-path LOAD_ENGINE_PATH] [--test-mmaction2] [--mmaction2-config MMACTION2_CONFIG] [--mmaction2-checkpoint MMACTION2_CHECKPOINT] [--test-cpp] [--cpp-result-path CPP_RESULT_PATH] optional arguments: -h, --help show this help message and exit @@ -54,8 +55,18 @@ optional arguments: Path to MMAction2 config file --mmaction2-checkpoint MMACTION2_CHECKPOINT Path to MMAction2 checkpoint url or file path + --test-cpp Compare Python API results with C++ API results + --cpp-result-path CPP_RESULT_PATH + Path to C++ API results ``` ++ Step 4: Test C++ API. + + Mocify Configs in `tsm_r50.cpp`. + + Build from source code: `mkdir build && cd build && cmake .. && make` + + Generate Engine file: `./tsm_r50 -s` + + Inference with genrated engine file and write predictions to local: `./tsm_r50 -d` + + Compare results with Python API: `python tsm_r50.py --tensorrt-weights /path/to/tensorrt.weights --test-cpp --cpp-result-file /path/to/cpp-result.txt` + ## TODO + [x] Python Shift module. @@ -63,4 +74,4 @@ optional arguments: + [x] Python API Definition + [x] Test with mmaction2 demo + [x] Tutorial -+ [ ] C++ API Definition ++ [x] C++ API Definition diff --git a/tsm/demo.sh b/tsm/demo.sh index 33b17a5..d8f0096 100644 --- a/tsm/demo.sh +++ b/tsm/demo.sh @@ -5,16 +5,16 @@ wget https://download.openmmlab.com/mmaction/recognition/tsm/tsm_r50_1x1x8_50e_k # Step 2: Convert pytorch checkpoints to TensorRT weights python gen_wts.py tsm_r50_1x1x8_50e_kinetics400_rgb_20200607-af7fb746.pth --out-filename ./tsm_r50_kinetics400_mmaction2.wts -# Step 3: Skip this step since we use default settings. - -# Step 4: Inference -# 1) Save local engine file to `./tsm_r50_kinetics400_mmaction2.trt`. +# Step 3: Test Python API. +# 3.1 Skip this step since we use default settings. +# 3.2 Inference +# 3.2.1 Save local engine file to `./tsm_r50_kinetics400_mmaction2.trt`. python tsm_r50.py \ --tensorrt-weights ./tsm_r50_kinetics400_mmaction2.wts \ --save-engine-path ./tsm_r50_kinetics400_mmaction2.trt -# 2) Predict the recognition result using a single video `demo.mp4`. -# Should print `Result class id 6`, aka `arm wrestling` +# 3.2.2 Predict the recognition result using a single video `demo.mp4`. +# Should print `Result class id 6`, aka `arm wrestling` # Download demo video wget https://raw.githubusercontent.com/open-mmlab/mmaction2/master/demo/demo.mp4 # # use *.wts as input @@ -24,8 +24,8 @@ wget https://raw.githubusercontent.com/open-mmlab/mmaction2/master/demo/demo.mp4 python tsm_r50.py --load-engine-path ./tsm_r50_kinetics400_mmaction2.trt \ --input-video ./demo.mp4 -# 3) Optional: Compare inference result with MMAction2 TSM-R50 model -# Have to install MMAction2 First, please refer to https://github.com/open-mmlab/mmaction2/blob/master/docs/install.md +# 3.2.3 Optional: Compare inference result with MMAction2 TSM-R50 model +# Have to install MMAction2 First, please refer to https://github.com/open-mmlab/mmaction2/blob/master/docs/install.md # pip3 install pytest-runner # pip3 install mmcv # pip3 install mmaction2 @@ -41,3 +41,15 @@ python tsm_r50.py --load-engine-path ./tsm_r50_kinetics400_mmaction2.trt \ # --test-mmaction2 \ # --mmaction2-config mmaction2_tsm_r50_config.py \ # --mmaction2-checkpoint tsm_r50_1x1x8_50e_kinetics400_rgb_20200607-af7fb746.pth + +# Step 4: Test Python API. +# 4.1 Skip this step since we use default settings. +# 4.2 Build CPP +mkdir build && cd build && cmake .. && make +# 4.3 Generate Engine file +./tsm_r50 -s +# 4.4 Get Predictions +./tsm_r50 -d +# 4.5 Compare C++ Results with Python Results +cd .. +python tsm_r50.py --test-cpp --tensorrt-weights ./tsm_r50_kinetics400_mmaction2.wts diff --git a/tsm/logging.h b/tsm/logging.h new file mode 100644 index 0000000..602b69f --- /dev/null +++ b/tsm/logging.h @@ -0,0 +1,503 @@ +/* + * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TENSORRT_LOGGING_H +#define TENSORRT_LOGGING_H + +#include "NvInferRuntimeCommon.h" +#include +#include +#include +#include +#include +#include +#include + +using Severity = nvinfer1::ILogger::Severity; + +class LogStreamConsumerBuffer : public std::stringbuf +{ +public: + LogStreamConsumerBuffer(std::ostream& stream, const std::string& prefix, bool shouldLog) + : mOutput(stream) + , mPrefix(prefix) + , mShouldLog(shouldLog) + { + } + + LogStreamConsumerBuffer(LogStreamConsumerBuffer&& other) + : mOutput(other.mOutput) + { + } + + ~LogStreamConsumerBuffer() + { + // std::streambuf::pbase() gives a pointer to the beginning of the buffered part of the output sequence + // std::streambuf::pptr() gives a pointer to the current position of the output sequence + // if the pointer to the beginning is not equal to the pointer to the current position, + // call putOutput() to log the output to the stream + if (pbase() != pptr()) + { + putOutput(); + } + } + + // synchronizes the stream buffer and returns 0 on success + // synchronizing the stream buffer consists of inserting the buffer contents into the stream, + // resetting the buffer and flushing the stream + virtual int sync() + { + putOutput(); + return 0; + } + + void putOutput() + { + if (mShouldLog) + { + // prepend timestamp + std::time_t timestamp = std::time(nullptr); + tm* tm_local = std::localtime(×tamp); + std::cout << "["; + std::cout << std::setw(2) << std::setfill('0') << 1 + tm_local->tm_mon << "/"; + std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_mday << "/"; + std::cout << std::setw(4) << std::setfill('0') << 1900 + tm_local->tm_year << "-"; + std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_hour << ":"; + std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_min << ":"; + std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_sec << "] "; + // std::stringbuf::str() gets the string contents of the buffer + // insert the buffer contents pre-appended by the appropriate prefix into the stream + mOutput << mPrefix << str(); + // set the buffer to empty + str(""); + // flush the stream + mOutput.flush(); + } + } + + void setShouldLog(bool shouldLog) + { + mShouldLog = shouldLog; + } + +private: + std::ostream& mOutput; + std::string mPrefix; + bool mShouldLog; +}; + +//! +//! \class LogStreamConsumerBase +//! \brief Convenience object used to initialize LogStreamConsumerBuffer before std::ostream in LogStreamConsumer +//! +class LogStreamConsumerBase +{ +public: + LogStreamConsumerBase(std::ostream& stream, const std::string& prefix, bool shouldLog) + : mBuffer(stream, prefix, shouldLog) + { + } + +protected: + LogStreamConsumerBuffer mBuffer; +}; + +//! +//! \class LogStreamConsumer +//! \brief Convenience object used to facilitate use of C++ stream syntax when logging messages. +//! Order of base classes is LogStreamConsumerBase and then std::ostream. +//! This is because the LogStreamConsumerBase class is used to initialize the LogStreamConsumerBuffer member field +//! in LogStreamConsumer and then the address of the buffer is passed to std::ostream. +//! This is necessary to prevent the address of an uninitialized buffer from being passed to std::ostream. +//! Please do not change the order of the parent classes. +//! +class LogStreamConsumer : protected LogStreamConsumerBase, public std::ostream +{ +public: + //! \brief Creates a LogStreamConsumer which logs messages with level severity. + //! Reportable severity determines if the messages are severe enough to be logged. + LogStreamConsumer(Severity reportableSeverity, Severity severity) + : LogStreamConsumerBase(severityOstream(severity), severityPrefix(severity), severity <= reportableSeverity) + , std::ostream(&mBuffer) // links the stream buffer with the stream + , mShouldLog(severity <= reportableSeverity) + , mSeverity(severity) + { + } + + LogStreamConsumer(LogStreamConsumer&& other) + : LogStreamConsumerBase(severityOstream(other.mSeverity), severityPrefix(other.mSeverity), other.mShouldLog) + , std::ostream(&mBuffer) // links the stream buffer with the stream + , mShouldLog(other.mShouldLog) + , mSeverity(other.mSeverity) + { + } + + void setReportableSeverity(Severity reportableSeverity) + { + mShouldLog = mSeverity <= reportableSeverity; + mBuffer.setShouldLog(mShouldLog); + } + +private: + static std::ostream& severityOstream(Severity severity) + { + return severity >= Severity::kINFO ? std::cout : std::cerr; + } + + static std::string severityPrefix(Severity severity) + { + switch (severity) + { + case Severity::kINTERNAL_ERROR: return "[F] "; + case Severity::kERROR: return "[E] "; + case Severity::kWARNING: return "[W] "; + case Severity::kINFO: return "[I] "; + case Severity::kVERBOSE: return "[V] "; + default: assert(0); return ""; + } + } + + bool mShouldLog; + Severity mSeverity; +}; + +//! \class Logger +//! +//! \brief Class which manages logging of TensorRT tools and samples +//! +//! \details This class provides a common interface for TensorRT tools and samples to log information to the console, +//! and supports logging two types of messages: +//! +//! - Debugging messages with an associated severity (info, warning, error, or internal error/fatal) +//! - Test pass/fail messages +//! +//! The advantage of having all samples use this class for logging as opposed to emitting directly to stdout/stderr is +//! that the logic for controlling the verbosity and formatting of sample output is centralized in one location. +//! +//! In the future, this class could be extended to support dumping test results to a file in some standard format +//! (for example, JUnit XML), and providing additional metadata (e.g. timing the duration of a test run). +//! +//! TODO: For backwards compatibility with existing samples, this class inherits directly from the nvinfer1::ILogger +//! interface, which is problematic since there isn't a clean separation between messages coming from the TensorRT +//! library and messages coming from the sample. +//! +//! In the future (once all samples are updated to use Logger::getTRTLogger() to access the ILogger) we can refactor the +//! class to eliminate the inheritance and instead make the nvinfer1::ILogger implementation a member of the Logger +//! object. + +class Logger : public nvinfer1::ILogger +{ +public: + Logger(Severity severity = Severity::kWARNING) + : mReportableSeverity(severity) + { + } + + //! + //! \enum TestResult + //! \brief Represents the state of a given test + //! + enum class TestResult + { + kRUNNING, //!< The test is running + kPASSED, //!< The test passed + kFAILED, //!< The test failed + kWAIVED //!< The test was waived + }; + + //! + //! \brief Forward-compatible method for retrieving the nvinfer::ILogger associated with this Logger + //! \return The nvinfer1::ILogger associated with this Logger + //! + //! TODO Once all samples are updated to use this method to register the logger with TensorRT, + //! we can eliminate the inheritance of Logger from ILogger + //! + nvinfer1::ILogger& getTRTLogger() + { + return *this; + } + + //! + //! \brief Implementation of the nvinfer1::ILogger::log() virtual method + //! + //! Note samples should not be calling this function directly; it will eventually go away once we eliminate the + //! inheritance from nvinfer1::ILogger + //! + void log(Severity severity, const char* msg) override + { + LogStreamConsumer(mReportableSeverity, severity) << "[TRT] " << std::string(msg) << std::endl; + } + + //! + //! \brief Method for controlling the verbosity of logging output + //! + //! \param severity The logger will only emit messages that have severity of this level or higher. + //! + void setReportableSeverity(Severity severity) + { + mReportableSeverity = severity; + } + + //! + //! \brief Opaque handle that holds logging information for a particular test + //! + //! This object is an opaque handle to information used by the Logger to print test results. + //! The sample must call Logger::defineTest() in order to obtain a TestAtom that can be used + //! with Logger::reportTest{Start,End}(). + //! + class TestAtom + { + public: + TestAtom(TestAtom&&) = default; + + private: + friend class Logger; + + TestAtom(bool started, const std::string& name, const std::string& cmdline) + : mStarted(started) + , mName(name) + , mCmdline(cmdline) + { + } + + bool mStarted; + std::string mName; + std::string mCmdline; + }; + + //! + //! \brief Define a test for logging + //! + //! \param[in] name The name of the test. This should be a string starting with + //! "TensorRT" and containing dot-separated strings containing + //! the characters [A-Za-z0-9_]. + //! For example, "TensorRT.sample_googlenet" + //! \param[in] cmdline The command line used to reproduce the test + // + //! \return a TestAtom that can be used in Logger::reportTest{Start,End}(). + //! + static TestAtom defineTest(const std::string& name, const std::string& cmdline) + { + return TestAtom(false, name, cmdline); + } + + //! + //! \brief A convenience overloaded version of defineTest() that accepts an array of command-line arguments + //! as input + //! + //! \param[in] name The name of the test + //! \param[in] argc The number of command-line arguments + //! \param[in] argv The array of command-line arguments (given as C strings) + //! + //! \return a TestAtom that can be used in Logger::reportTest{Start,End}(). + static TestAtom defineTest(const std::string& name, int argc, char const* const* argv) + { + auto cmdline = genCmdlineString(argc, argv); + return defineTest(name, cmdline); + } + + //! + //! \brief Report that a test has started. + //! + //! \pre reportTestStart() has not been called yet for the given testAtom + //! + //! \param[in] testAtom The handle to the test that has started + //! + static void reportTestStart(TestAtom& testAtom) + { + reportTestResult(testAtom, TestResult::kRUNNING); + assert(!testAtom.mStarted); + testAtom.mStarted = true; + } + + //! + //! \brief Report that a test has ended. + //! + //! \pre reportTestStart() has been called for the given testAtom + //! + //! \param[in] testAtom The handle to the test that has ended + //! \param[in] result The result of the test. Should be one of TestResult::kPASSED, + //! TestResult::kFAILED, TestResult::kWAIVED + //! + static void reportTestEnd(const TestAtom& testAtom, TestResult result) + { + assert(result != TestResult::kRUNNING); + assert(testAtom.mStarted); + reportTestResult(testAtom, result); + } + + static int reportPass(const TestAtom& testAtom) + { + reportTestEnd(testAtom, TestResult::kPASSED); + return EXIT_SUCCESS; + } + + static int reportFail(const TestAtom& testAtom) + { + reportTestEnd(testAtom, TestResult::kFAILED); + return EXIT_FAILURE; + } + + static int reportWaive(const TestAtom& testAtom) + { + reportTestEnd(testAtom, TestResult::kWAIVED); + return EXIT_SUCCESS; + } + + static int reportTest(const TestAtom& testAtom, bool pass) + { + return pass ? reportPass(testAtom) : reportFail(testAtom); + } + + Severity getReportableSeverity() const + { + return mReportableSeverity; + } + +private: + //! + //! \brief returns an appropriate string for prefixing a log message with the given severity + //! + static const char* severityPrefix(Severity severity) + { + switch (severity) + { + case Severity::kINTERNAL_ERROR: return "[F] "; + case Severity::kERROR: return "[E] "; + case Severity::kWARNING: return "[W] "; + case Severity::kINFO: return "[I] "; + case Severity::kVERBOSE: return "[V] "; + default: assert(0); return ""; + } + } + + //! + //! \brief returns an appropriate string for prefixing a test result message with the given result + //! + static const char* testResultString(TestResult result) + { + switch (result) + { + case TestResult::kRUNNING: return "RUNNING"; + case TestResult::kPASSED: return "PASSED"; + case TestResult::kFAILED: return "FAILED"; + case TestResult::kWAIVED: return "WAIVED"; + default: assert(0); return ""; + } + } + + //! + //! \brief returns an appropriate output stream (cout or cerr) to use with the given severity + //! + static std::ostream& severityOstream(Severity severity) + { + return severity >= Severity::kINFO ? std::cout : std::cerr; + } + + //! + //! \brief method that implements logging test results + //! + static void reportTestResult(const TestAtom& testAtom, TestResult result) + { + severityOstream(Severity::kINFO) << "&&&& " << testResultString(result) << " " << testAtom.mName << " # " + << testAtom.mCmdline << std::endl; + } + + //! + //! \brief generate a command line string from the given (argc, argv) values + //! + static std::string genCmdlineString(int argc, char const* const* argv) + { + std::stringstream ss; + for (int i = 0; i < argc; i++) + { + if (i > 0) + ss << " "; + ss << argv[i]; + } + return ss.str(); + } + + Severity mReportableSeverity; +}; + +namespace +{ + +//! +//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kVERBOSE +//! +//! Example usage: +//! +//! LOG_VERBOSE(logger) << "hello world" << std::endl; +//! +inline LogStreamConsumer LOG_VERBOSE(const Logger& logger) +{ + return LogStreamConsumer(logger.getReportableSeverity(), Severity::kVERBOSE); +} + +//! +//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINFO +//! +//! Example usage: +//! +//! LOG_INFO(logger) << "hello world" << std::endl; +//! +inline LogStreamConsumer LOG_INFO(const Logger& logger) +{ + return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINFO); +} + +//! +//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kWARNING +//! +//! Example usage: +//! +//! LOG_WARN(logger) << "hello world" << std::endl; +//! +inline LogStreamConsumer LOG_WARN(const Logger& logger) +{ + return LogStreamConsumer(logger.getReportableSeverity(), Severity::kWARNING); +} + +//! +//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kERROR +//! +//! Example usage: +//! +//! LOG_ERROR(logger) << "hello world" << std::endl; +//! +inline LogStreamConsumer LOG_ERROR(const Logger& logger) +{ + return LogStreamConsumer(logger.getReportableSeverity(), Severity::kERROR); +} + +//! +//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINTERNAL_ERROR +// ("fatal" severity) +//! +//! Example usage: +//! +//! LOG_FATAL(logger) << "hello world" << std::endl; +//! +inline LogStreamConsumer LOG_FATAL(const Logger& logger) +{ + return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINTERNAL_ERROR); +} + +} // anonymous namespace + +#endif // TENSORRT_LOGGING_H diff --git a/tsm/tsm_r50.cpp b/tsm/tsm_r50.cpp new file mode 100644 index 0000000..3a500f2 --- /dev/null +++ b/tsm/tsm_r50.cpp @@ -0,0 +1,422 @@ +#include "NvInfer.h" +#include "cuda_runtime_api.h" +#include "logging.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(status) \ + do\ + {\ + auto ret = (status);\ + if (ret != 0)\ + {\ + std::cerr << "Cuda failure: " << ret << std::endl;\ + abort();\ + }\ + } while (0) + +static const int INPUT_H = 224; +static const int INPUT_W = 224; +static const int OUTPUT_SIZE = 400; +static const int NUM_SEGMENTS = 8; +static const int SHIFT_DIV = 8; + +const char* INPUT_BLOB_NAME = "data"; +const char* OUTPUT_BLOB_NAME = "prob"; +const char* WEIGHTS_PATH = "../tsm_r50_kinetics400_mmaction2.wts"; +const char* ENGINE_PATH = "./tsm_r50_kinetics400_mmaction2_cpp.trt"; +const char* RESULT_PATH = "./result.txt"; + +using namespace nvinfer1; + +static Logger gLogger; + +// Load weights from files shared with TensorRT samples. +// TensorRT weight files have a simple space delimited format: +// [type] [size] +std::map loadWeights(const std::string file) +{ + std::cout << "Loading weights: " << file << std::endl; + std::map weightMap; + + // Open weights file + std::ifstream input(file); + assert(input.is_open() && "Unable to load weight file."); + + // Read number of weight blobs + int32_t count; + input >> count; + assert(count > 0 && "Invalid weight map file."); + + while (count--) + { + Weights wt{DataType::kFLOAT, nullptr, 0}; + uint32_t size; + + // Read name and type of blob + std::string name; + input >> name >> std::dec >> size; + wt.type = DataType::kFLOAT; + + // Load blob + uint32_t* val = reinterpret_cast(malloc(sizeof(val) * size)); + for (uint32_t x = 0, y = size; x < y; ++x) + { + input >> std::hex >> val[x]; + } + wt.values = val; + + wt.count = size; + weightMap[name] = wt; + } + + return weightMap; +} + +void print(char* name, ITensor* tensor) { + Dims dim = tensor->getDimensions(); + std::cout << name << " " << dim.d[0] << " " << dim.d[1] << " " << dim.d[2] << " " << dim.d[3] <(malloc(sizeof(zeros) * fold*inputShape.d[2]*inputShape.d[3])); + memset(zeros, 0, sizeof(zeros) * fold*inputShape.d[2]*inputShape.d[3]); + Weights zeros_weights{DataType::kFLOAT, zeros, fold*inputShape.d[2]*inputShape.d[3]}; + + // left + ISliceLayer* left1 = network->addSlice(input, Dims4{1, 0, 0, 0}, Dims4{numSegments - 1, fold, inputShape.d[2], inputShape.d[3]}, Dims4{1, 1, 1, 1}); + IConstantLayer* left2 = network->addConstant(Dims4{1, fold, inputShape.d[2], inputShape.d[3]}, zeros_weights); + ITensor* tensorsLeft[] = {left1->getOutput(0), left2->getOutput(0)}; + IConcatenationLayer* left = network->addConcatenation(tensorsLeft, 2); + left->setAxis(0); + + // mid + IConstantLayer* mid1 = network->addConstant(Dims4{1, fold, inputShape.d[2], inputShape.d[3]}, zeros_weights); + ISliceLayer* mid2 = network->addSlice(input, Dims4{0, fold, 0, 0}, Dims4{numSegments - 1, fold, inputShape.d[2], inputShape.d[3]}, Dims4{1, 1, 1, 1}); + ITensor* tensorsMid[] = {mid1->getOutput(0), mid2->getOutput(0)}; + IConcatenationLayer* mid = network->addConcatenation(tensorsMid, 2); + mid->setAxis(0); + + // right + ISliceLayer* right = network->addSlice(input, Dims4{0, 2 * fold, 0, 0}, Dims4{numSegments, inputShape.d[1] - 2 * fold, inputShape.d[2], inputShape.d[3]}, Dims4{1, 1, 1, 1}); + + // concatenate left/mid/right + ITensor* tensors[] = {left->getOutput(0), mid->getOutput(0), right->getOutput(0)}; + IConcatenationLayer* concat = network->addConcatenation(tensors, 3); + concat->setAxis(1); + return concat; +} + +IScaleLayer* addBatchNorm2d(INetworkDefinition *network, std::map& weightMap, ITensor& input, std::string lname, float eps) { + float *gamma = (float*)weightMap[lname + ".weight"].values; + float *beta = (float*)weightMap[lname + ".bias"].values; + float *mean = (float*)weightMap[lname + ".running_mean"].values; + float *var = (float*)weightMap[lname + ".running_var"].values; + int len = weightMap[lname + ".running_var"].count; + + float *scval = reinterpret_cast(malloc(sizeof(float) * len)); + for (int i = 0; i < len; i++) { + scval[i] = gamma[i] / sqrt(var[i] + eps); + } + Weights scale{DataType::kFLOAT, scval, len}; + + float *shval = reinterpret_cast(malloc(sizeof(float) * len)); + for (int i = 0; i < len; i++) { + shval[i] = beta[i] - mean[i] * gamma[i] / sqrt(var[i] + eps); + } + Weights shift{DataType::kFLOAT, shval, len}; + + float *pval = reinterpret_cast(malloc(sizeof(float) * len)); + for (int i = 0; i < len; i++) { + pval[i] = 1.0; + } + Weights power{DataType::kFLOAT, pval, len}; + + weightMap[lname + ".scale"] = scale; + weightMap[lname + ".shift"] = shift; + weightMap[lname + ".power"] = power; + IScaleLayer* scale_1 = network->addScale(input, ScaleMode::kCHANNEL, shift, scale, power); + assert(scale_1); + return scale_1; +} + +IActivationLayer* bottleneck(INetworkDefinition *network, std::map& weightMap, ITensor& input, int inch, int outch, int stride, std::string lname, Dims4 inputShape) { + IConcatenationLayer* shift = addShift(network, input, inputShape, NUM_SEGMENTS, SHIFT_DIV); + assert(shift); + + Weights emptywts{DataType::kFLOAT, nullptr, 0}; + + IConvolutionLayer* conv1 = network->addConvolution(*shift->getOutput(0), outch, DimsHW{1, 1}, weightMap[lname + "conv1.weight"], emptywts); + + IScaleLayer* bn1 = addBatchNorm2d(network, weightMap, *conv1->getOutput(0), lname + "bn1", 1e-5); + + IActivationLayer* relu1 = network->addActivation(*bn1->getOutput(0), ActivationType::kRELU); + assert(relu1); + + IConvolutionLayer* conv2 = network->addConvolution(*relu1->getOutput(0), outch, DimsHW{3, 3}, weightMap[lname + "conv2.weight"], emptywts); + assert(conv2); + conv2->setStride(DimsHW{stride, stride}); + conv2->setPadding(DimsHW{1, 1}); + + IScaleLayer* bn2 = addBatchNorm2d(network, weightMap, *conv2->getOutput(0), lname + "bn2", 1e-5); + + IActivationLayer* relu2 = network->addActivation(*bn2->getOutput(0), ActivationType::kRELU); + assert(relu2); + + IConvolutionLayer* conv3 = network->addConvolution(*relu2->getOutput(0), outch * 4, DimsHW{1, 1}, weightMap[lname + "conv3.weight"], emptywts); + assert(conv3); + + IScaleLayer* bn3 = addBatchNorm2d(network, weightMap, *conv3->getOutput(0), lname + "bn3", 1e-5); + + IElementWiseLayer* ew1; + if (stride != 1 || inch != outch * 4) { + IConvolutionLayer* conv4 = network->addConvolution(input, outch * 4, DimsHW{1, 1}, weightMap[lname + "downsample.0.weight"], emptywts); + assert(conv4); + conv4->setStride(DimsHW{stride, stride}); + + IScaleLayer* bn4 = addBatchNorm2d(network, weightMap, *conv4->getOutput(0), lname + "downsample.1", 1e-5); + ew1 = network->addElementWise(*bn4->getOutput(0), *bn3->getOutput(0), ElementWiseOperation::kSUM); + } else { + ew1 = network->addElementWise(input, *bn3->getOutput(0), ElementWiseOperation::kSUM); + } + IActivationLayer* relu3 = network->addActivation(*ew1->getOutput(0), ActivationType::kRELU); + assert(relu3); + return relu3; +} + +// Creat the engine using only the API and not any parser. +ICudaEngine* createEngine(unsigned int maxBatchSize, IBuilder* builder, DataType dt) +{ + INetworkDefinition* network = builder->createNetwork(); + + // Create input tensor of shape {NUM_SEGMENTS, 3, INPUT_H, INPUT_W } with name INPUT_BLOB_NAME + ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims4{NUM_SEGMENTS, 3, INPUT_H, INPUT_W}); + assert(data); + print("input", data); + + std::map weightMap = loadWeights(WEIGHTS_PATH); + Weights emptywts{DataType::kFLOAT, nullptr, 0}; + + IConvolutionLayer* conv1 = network->addConvolution(*data, 64, DimsHW{7, 7}, weightMap["conv1.weight"], emptywts); + assert(conv1); + conv1->setStride(DimsHW{2, 2}); + conv1->setPadding(DimsHW{3, 3}); + + IScaleLayer* bn1 = addBatchNorm2d(network, weightMap, *conv1->getOutput(0), "bn1", 1e-5); + + // Add activation layer using the ReLU algorithm. + IActivationLayer* relu1 = network->addActivation(*bn1->getOutput(0), ActivationType::kRELU); + assert(relu1); + + // Add max pooling layer with stride of 2x2 and kernel size of 2x2. + IPoolingLayer* pool1 = network->addPooling(*relu1->getOutput(0), PoolingType::kMAX, DimsHW{3, 3}); + assert(pool1); + pool1->setStride(DimsHW{2, 2}); + pool1->setPadding(DimsHW{1, 1}); + + int curHeight = int(INPUT_H / 4); + int curWidth = int(INPUT_W / 4); + IActivationLayer* x = bottleneck(network, weightMap, *pool1->getOutput(0), 64, 64, 1, "layer1.0.", Dims4{NUM_SEGMENTS, 64, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 256, 64, 1, "layer1.1.", Dims4{NUM_SEGMENTS, 256, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 256, 64, 1, "layer1.2.", Dims4{NUM_SEGMENTS, 256, curHeight, curWidth}); + + x = bottleneck(network, weightMap, *x->getOutput(0), 256, 128, 2, "layer2.0.", Dims4{NUM_SEGMENTS, 256, curHeight, curWidth}); + curHeight = int(INPUT_H / 8); + curWidth = int(INPUT_W / 8); + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 128, 1, "layer2.1.", Dims4{NUM_SEGMENTS, 512, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 128, 1, "layer2.2.", Dims4{NUM_SEGMENTS, 512, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 128, 1, "layer2.3.", Dims4{NUM_SEGMENTS, 512, curHeight, curWidth}); + + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 256, 2, "layer3.0.", Dims4{NUM_SEGMENTS, 512, curHeight, curWidth}); + curHeight = int(INPUT_H / 16); + curWidth = int(INPUT_W / 16); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "layer3.1.", Dims4{NUM_SEGMENTS, 1024, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "layer3.2.", Dims4{NUM_SEGMENTS, 1024, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "layer3.3.", Dims4{NUM_SEGMENTS, 1024, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "layer3.4.", Dims4{NUM_SEGMENTS, 1024, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "layer3.5.", Dims4{NUM_SEGMENTS, 1024, curHeight, curWidth}); + + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 512, 2, "layer4.0.", Dims4{NUM_SEGMENTS, 1024, curHeight, curWidth}); + curHeight = int(INPUT_H / 32); + curWidth = int(INPUT_W / 32); + x = bottleneck(network, weightMap, *x->getOutput(0), 2048, 512, 1, "layer4.1.", Dims4{NUM_SEGMENTS, 2048, curHeight, curWidth}); + x = bottleneck(network, weightMap, *x->getOutput(0), 2048, 512, 1, "layer4.2.", Dims4{NUM_SEGMENTS, 2048, curHeight, curWidth}); + + IPoolingLayer* pool2 = network->addPooling(*x->getOutput(0), PoolingType::kAVERAGE, DimsHW{curHeight, curWidth}); + assert(pool2); + pool2->setStride(DimsHW{1, 1}); + + IFullyConnectedLayer* fc1 = network->addFullyConnected(*pool2->getOutput(0), OUTPUT_SIZE, weightMap["fc.weight"], weightMap["fc.bias"]); + assert(fc1); + + IReduceLayer* reduce = network->addReduce(*fc1->getOutput(0), ReduceOperation::kAVG, 1, false); + assert(reduce); + + ISoftMaxLayer* softmax = network->addSoftMax(*reduce->getOutput(0)); + assert(softmax); + softmax->setAxes(1); + + softmax->getOutput(0)->setName(OUTPUT_BLOB_NAME); + network->markOutput(*softmax->getOutput(0)); + + // Build engine + builder->setMaxBatchSize(maxBatchSize); + ICudaEngine* engine = builder->buildCudaEngine(*network); + + // Don't need the network any more + network->destroy(); + + // Release host memory + for (auto& mem : weightMap) + { + free((void*) (mem.second.values)); + } + + return engine; +} + +void APIToModel(unsigned int maxBatchSize, IHostMemory** modelStream) +{ + // Create builder + IBuilder* builder = createInferBuilder(gLogger); + + // Create model to populate the network, then set the outputs and create an engine + ICudaEngine* engine = createEngine(maxBatchSize, builder, DataType::kFLOAT); + assert(engine != nullptr); + + // Serialize the engine + (*modelStream) = engine->serialize(); + + // Close everything down + engine->destroy(); + builder->destroy(); +} + +void doInference(IExecutionContext& context, float* input, float* output, int batchSize) +{ + const ICudaEngine& engine = context.getEngine(); + + // Pointers to input and output device buffers to pass to engine. + // Engine requires exactly IEngine::getNbBindings() number of buffers. + assert(engine.getNbBindings() == 2); + void* buffers[2]; + + // In order to bind the buffers, we need to know the names of the input and output tensors. + // Note that indices are guaranteed to be less than IEngine::getNbBindings() + const int inputIndex = engine.getBindingIndex(INPUT_BLOB_NAME); + const int outputIndex = engine.getBindingIndex(OUTPUT_BLOB_NAME); + + // Create GPU buffers on device + CHECK(cudaMalloc(&buffers[inputIndex], batchSize * NUM_SEGMENTS * 3 * INPUT_H * INPUT_W * sizeof(float))); + CHECK(cudaMalloc(&buffers[outputIndex], batchSize * OUTPUT_SIZE * sizeof(float))); + + // Create stream + cudaStream_t stream; + CHECK(cudaStreamCreate(&stream)); + + // DMA input batch data to device, infer on the batch asynchronously, and DMA output back to host + CHECK(cudaMemcpyAsync(buffers[inputIndex], input, batchSize * NUM_SEGMENTS * 3 * INPUT_H * INPUT_W * sizeof(float), cudaMemcpyHostToDevice, stream)); + context.enqueue(batchSize, buffers, stream, nullptr); + CHECK(cudaMemcpyAsync(output, buffers[outputIndex], batchSize * OUTPUT_SIZE * sizeof(float), cudaMemcpyDeviceToHost, stream)); + cudaStreamSynchronize(stream); + + // Release stream and buffers + cudaStreamDestroy(stream); + CHECK(cudaFree(buffers[inputIndex])); + CHECK(cudaFree(buffers[outputIndex])); +} + +int main(int argc, char** argv) +{ + if (argc != 2) { + std::cerr << "arguments not right!" << std::endl; + std::cerr << "./tsm_r50 -s // serialize model to plan file" << std::endl; + std::cerr << "./tsm_r50 -d // deserialize plan file and run inference" << std::endl; + return -1; + } + + // create a model using the API directly and serialize it to a stream + char *trtModelStream{nullptr}; + size_t size{0}; + + if (std::string(argv[1]) == "-s") { + IHostMemory* modelStream{nullptr}; + APIToModel(1, &modelStream); + assert(modelStream != nullptr); + + std::ofstream p(ENGINE_PATH, std::ios::binary); + if (!p) + { + std::cerr << "could not open plan output file" << std::endl; + return -1; + } + p.write(reinterpret_cast(modelStream->data()), modelStream->size()); + modelStream->destroy(); + return 1; + } else if (std::string(argv[1]) == "-d") { + std::ifstream file(ENGINE_PATH, std::ios::binary); + if (file.good()) { + file.seekg(0, file.end); + size = file.tellg(); + file.seekg(0, file.beg); + trtModelStream = new char[size]; + assert(trtModelStream); + file.read(trtModelStream, size); + file.close(); + } + } else { + return -1; + } + + + // Subtract mean from image + static float data[NUM_SEGMENTS * 3 * INPUT_H * INPUT_W]; + for (int i = 0; i < NUM_SEGMENTS * 3 * INPUT_H * INPUT_W; i++) + data[i] = 1.0; + + IRuntime* runtime = createInferRuntime(gLogger); + assert(runtime != nullptr); + ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size, nullptr); + assert(engine != nullptr); + IExecutionContext* context = engine->createExecutionContext(); + assert(context != nullptr); + delete[] trtModelStream; + + // Run inference + static float prob[OUTPUT_SIZE]; + doInference(*context, data, prob, 1); + + // Destroy the engine + context->destroy(); + engine->destroy(); + runtime->destroy(); + + // Print histogram of the output distribution + std::cout << "\nOutput:\n\n"; + for (unsigned int i = 0; i < 10; i++) + { + std::cout << prob[i] << ", "; + } + std::cout << std::endl; + for (unsigned int i = 0; i < 10; i++) + { + std::cout << prob[OUTPUT_SIZE - 10 + i] << ", "; + } + std::cout << std::endl; + std::fstream writer(RESULT_PATH, std::ios::out); + + writer << prob[0]; + for(int i = 1; i < OUTPUT_SIZE ; i++) { + writer << " " << prob[i]; + } + writer.close(); + + return 0; +} diff --git a/tsm/tsm_r50.py b/tsm/tsm_r50.py index 767dac6..2a2980a 100644 --- a/tsm/tsm_r50.py +++ b/tsm/tsm_r50.py @@ -399,7 +399,33 @@ def main(args): assert_array_almost_equal(host_out.reshape(-1), pytorch_results.reshape(-1), decimal=4) - print("TEST PASSED") + print("MMAction2 TEST PASSED") + + if args.test_cpp: + assert args.cpp_result_path, "Should set --cpp-result-path" + assert os.path.exists(args.cpp_result_path),\ + f"{args.cpp_result} doesn't exist" + + # C++ API fixed inputs + inputs = np.ones((BATCH_SIZE, NUM_SEGMENTS, 3, INPUT_H, INPUT_W), + dtype=np.float32) + + # TensorRT inference + np.copyto(host_in, inputs.ravel()) + do_inference(context, host_in, host_out, BATCH_SIZE) + + # Read cpp inference results + with open(args.cpp_result_path, "r") as f: + data = f.read().strip() + cpp_results = np.array([float(d) + for d in data.split(" ")]).astype(np.float32) + + # test + from numpy.testing import assert_array_almost_equal + assert_array_almost_equal(host_out.reshape(-1), + cpp_results.reshape(-1), + decimal=4) + print("CPP TEST PASSED") if args.input_video: # Get ONE prediction result from ONE video @@ -467,5 +493,12 @@ if __name__ == '__main__': type=str, default=None, help="Path to MMAction2 checkpoint url or file path") + parser.add_argument("--test-cpp", + action='store_true', + help="Compare Python API results with C++ API results") + parser.add_argument("--cpp-result-path", + type=str, + default='./build/result.txt', + help="Path to C++ API results") main(parser.parse_args())