From 93e728769d4f2446e71a7b8ef92c9d0a7df36d40 Mon Sep 17 00:00:00 2001 From: weiwei zhou Date: Fri, 11 Jun 2021 10:34:40 +0800 Subject: [PATCH] Add EfficientNet (#590) * create psenet create psenet with weight from tensorflow * delete some useless code * repalce tab with 4 blanks * fix network bug, rewrite post-processing pse algorithm * update readme * update readme * add RepVGG * fix typo * add hrnetseg w18 w32 w48 * add hrnetseg with ocr w18 w32 w48 * merge hrnet and small, add hrnet_ocr * fix warning * change project name * add efficientnet --- efficientnet/CMakeLists.txt | 27 ++ efficientnet/README.md | 45 +++ efficientnet/efficientnet.cpp | 280 +++++++++++++++++++ efficientnet/gen_wts.py | 16 ++ efficientnet/logging.h | 503 ++++++++++++++++++++++++++++++++++ efficientnet/utils.hpp | 251 +++++++++++++++++ 6 files changed, 1122 insertions(+) create mode 100644 efficientnet/CMakeLists.txt create mode 100644 efficientnet/README.md create mode 100644 efficientnet/efficientnet.cpp create mode 100644 efficientnet/gen_wts.py create mode 100644 efficientnet/logging.h create mode 100644 efficientnet/utils.hpp diff --git a/efficientnet/CMakeLists.txt b/efficientnet/CMakeLists.txt new file mode 100644 index 0000000..476fa01 --- /dev/null +++ b/efficientnet/CMakeLists.txt @@ -0,0 +1,27 @@ +cmake_minimum_required(VERSION 2.6) + +project(efficientnet) + +add_definitions(-std=c++11) + +option(CUDA_USE_STATIC_CUDA_RUNTIME OFF) +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_BUILD_TYPE Debug) + +find_package(CUDA REQUIRED) + +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(/usr/include/x86_64-linux-gnu/) +link_directories(/usr/lib/x86_64-linux-gnu/) + +add_executable(efficientnet ${PROJECT_SOURCE_DIR}/efficientnet.cpp) +target_link_libraries(efficientnet nvinfer) +target_link_libraries(efficientnet cudart) + +add_definitions(-O2 -pthread) + diff --git a/efficientnet/README.md b/efficientnet/README.md new file mode 100644 index 0000000..4fe81ed --- /dev/null +++ b/efficientnet/README.md @@ -0,0 +1,45 @@ +# EfficientNet + +A TensorRT implementation of EfficientNet. +For the Pytorch implementation, you can refer to [EfficientNet-PyTorch](https://github.com/lukemelas/EfficientNet-PyTorch) + +## How to run + +1. install `efficientnet_pytorch` +``` +pip install efficientnet_pytorch +``` + +2. gennerate `.wts` file +``` +python gen_wts.py +``` + +3. build + +``` +mkdir build +cd build +cmake .. +make +``` +4. serialize model to engine +``` +./efficientnet -s [.wts] [.engine] [b0 b1 b2 b3 ... b7] // serialize model to engine file +``` +such as +``` +./efficientnet -s ../efficientnet-b3.wts efficientnet-b3.engine b3 +``` +5. deserialize and do infer +``` +./efficientnet -d [.engine] [b0 b1 b2 b3 ... b7] // deserialize engine file and run inference +``` +such as +``` +./efficientnet -d efficientnet-b3.engine b3 +``` +6. see if the output is same as pytorch side + + +For more models, please refer to [tensorrtx](https://github.com/wang-xinyu/tensorrtx) diff --git a/efficientnet/efficientnet.cpp b/efficientnet/efficientnet.cpp new file mode 100644 index 0000000..bc19731 --- /dev/null +++ b/efficientnet/efficientnet.cpp @@ -0,0 +1,280 @@ +#include "NvInfer.h" +#include "cuda_runtime_api.h" +#include "logging.h" +#include +#include +#include +#include +#include +#include +#include "utils.hpp" + +#define USE_FP32 //USE_FP16 +#define INPUT_NAME "data" +#define OUTPUT_NAME "prob" +#define MAX_BATCH_SIZE 8 + +using namespace nvinfer1; +static Logger gLogger; + +static std::vector + block_args_list = { + BlockArgs{1, 3, 1, 1, 32, 16, 0.25, true}, + BlockArgs{2, 3, 2, 6, 16, 24, 0.25, true}, + BlockArgs{2, 5, 2, 6, 24, 40, 0.25, true}, + BlockArgs{3, 3, 2, 6, 40, 80, 0.25, true}, + BlockArgs{3, 5, 1, 6, 80, 112, 0.25, true}, + BlockArgs{4, 5, 2, 6, 112, 192, 0.25, true}, + BlockArgs{1, 3, 1, 6, 192, 320, 0.25, true}}; + +static std::map + global_params_map = { + // input_h,input_w,num_classes,batch_norm_epsilon, + // width_coefficient,depth_coefficient,depth_divisor, min_depth + {"b0", GlobalParams{224, 224, 1000, 0.001, 1.0, 1.0, 8, -1}}, + {"b1", GlobalParams{240, 240, 1000, 0.001, 1.0, 1.1, 8, -1}}, + {"b2", GlobalParams{260, 260, 1000, 0.001, 1.1, 1.2, 8, -1}}, + {"b3", GlobalParams{300, 300, 1000, 0.001, 1.2, 1.4, 8, -1}}, + {"b4", GlobalParams{380, 380, 1000, 0.001, 1.4, 1.8, 8, -1}}, + {"b5", GlobalParams{456, 456, 1000, 0.001, 1.6, 2.2, 8, -1}}, + {"b6", GlobalParams{528, 528, 1000, 0.001, 1.8, 2.6, 8, -1}}, + {"b7", GlobalParams{600, 600, 1000, 0.001, 2.0, 3.1, 8, -1}}, + {"b8", GlobalParams{672, 672, 1000, 0.001, 2.2, 3.6, 8, -1}}, + {"l2", GlobalParams{800, 800, 1000, 0.001, 4.3, 5.3, 8, -1}}, +}; + +ICudaEngine *createEngine(unsigned int maxBatchSize, IBuilder *builder, IBuilderConfig *config, DataType dt, std::string path_wts, std::vector block_args_list, GlobalParams global_params) +{ + float bn_eps = global_params.batch_norm_epsilon; + DimsHW image_size = DimsHW{global_params.input_h, global_params.input_w}; + + std::map weightMap = loadWeights(path_wts); + Weights emptywts{DataType::kFLOAT, nullptr, 0}; + INetworkDefinition *network = builder->createNetworkV2(0U); + ITensor *data = network->addInput(INPUT_NAME, dt, Dims3{3, global_params.input_h, global_params.input_w}); + assert(data); + + int out_channels = roundFilters(32, global_params); + auto conv_stem = addSamePaddingConv2d(network, weightMap, *data, out_channels, 3, 2, 1, 1, image_size, "_conv_stem"); + auto bn0 = addBatchNorm2d(network, weightMap, *conv_stem->getOutput(0), "_bn0", bn_eps); + auto swish0 = addSwish(network, *bn0->getOutput(0)); + ITensor *x = swish0->getOutput(0); + image_size = calculateOutputImageSize(image_size, 2); + int block_id = 0; + for (int i = 0; i < block_args_list.size(); i++) + { + BlockArgs block_args = block_args_list[i]; + + block_args.input_filters = roundFilters(block_args.input_filters, global_params); + block_args.output_filters = roundFilters(block_args.output_filters, global_params); + block_args.num_repeat = roundRepeats(block_args.num_repeat, global_params); + x = MBConvBlock(network, weightMap, *x, "_blocks." + std::to_string(block_id), block_args, global_params, image_size); + + assert(x); + block_id++; + image_size = calculateOutputImageSize(image_size, block_args.stride); + if (block_args.num_repeat > 1) + { + block_args.input_filters = block_args.output_filters; + block_args.stride = 1; + } + for (int r = 0; r < block_args.num_repeat - 1; r++) + { + x = MBConvBlock(network, weightMap, *x, "_blocks." + std::to_string(block_id), block_args, global_params, image_size); + block_id++; + } + } + out_channels = roundFilters(1280, global_params); + auto conv_head = addSamePaddingConv2d(network, weightMap, *x, out_channels, 1, 1, 1, 1, image_size, "_conv_head", false); + auto bn1 = addBatchNorm2d(network, weightMap, *conv_head->getOutput(0), "_bn1", bn_eps); + auto swish1 = addSwish(network, *bn1->getOutput(0)); + auto avg_pool = network->addPoolingNd(*swish1->getOutput(0), PoolingType::kAVERAGE, image_size); + + IFullyConnectedLayer *final = network->addFullyConnected(*avg_pool->getOutput(0), global_params.num_classes, weightMap["_fc.weight"], weightMap["_fc.bias"]); + assert(final); + + final->getOutput(0)->setName(OUTPUT_NAME); + network->markOutput(*final->getOutput(0)); + + // Build engine + builder->setMaxBatchSize(maxBatchSize); + config->setMaxWorkspaceSize(1 << 20); +#ifdef USE_FP16 + config->setFlag(BuilderFlag::kFP16); +#endif + std::cout << "build engine ..." << std::endl; + + ICudaEngine *engine = builder->buildEngineWithConfig(*network, *config); + assert(engine != nullptr); + + std::cout << "build finished" << std::endl; + // 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, std::string wtsPath, std::vector block_args_list, GlobalParams global_params) +{ + // Create builder + IBuilder *builder = createInferBuilder(gLogger); + IBuilderConfig *config = builder->createBuilderConfig(); + + // Create model to populate the network, then set the outputs and create an engine + ICudaEngine *engine = createEngine(maxBatchSize, builder, config, DataType::kFLOAT, wtsPath, block_args_list, global_params); + assert(engine != nullptr); + + // Serialize the engine + (*modelStream) = engine->serialize(); + + // Close everything down + engine->destroy(); + builder->destroy(); + config->destroy(); +} +void doInference(IExecutionContext &context, float *input, float *output, int batchSize, GlobalParams global_params) +{ + 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_NAME); + const int outputIndex = engine.getBindingIndex(OUTPUT_NAME); + + // Create GPU buffers on device + CHECK(cudaMalloc(&buffers[inputIndex], batchSize * 3 * global_params.input_h * global_params.input_w * sizeof(float))); + CHECK(cudaMalloc(&buffers[outputIndex], batchSize * global_params.num_classes * 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 * 3 * global_params.input_h * global_params.input_w * sizeof(float), cudaMemcpyHostToDevice, stream)); + context.enqueue(batchSize, buffers, stream, nullptr); + CHECK(cudaMemcpyAsync(output, buffers[outputIndex], batchSize * global_params.num_classes * sizeof(float), cudaMemcpyDeviceToHost, stream)); + cudaStreamSynchronize(stream); + + // Release stream and buffers + cudaStreamDestroy(stream); + CHECK(cudaFree(buffers[inputIndex])); + CHECK(cudaFree(buffers[outputIndex])); +} + +bool parse_args(int argc, char **argv, std::string &wts, std::string &engine, std::string &backbone) +{ + if (std::string(argv[1]) == "-s" && argc == 5) + { + wts = std::string(argv[2]); + engine = std::string(argv[3]); + backbone = std::string(argv[4]); + } + else if (std::string(argv[1]) == "-d" && argc == 4) + { + engine = std::string(argv[2]); + backbone = std::string(argv[3]); + } + else + { + return false; + } + return true; +} + +int main(int argc, char **argv) +{ + std::string wtsPath = ""; + std::string engine_name = ""; + std::string backbone = ""; + if (!parse_args(argc, argv, wtsPath, engine_name, backbone)) + { + std::cerr << "arguments not right!" << std::endl; + std::cerr << "./efficientnet -s [.wts] [.engine] [b0 b1 b2 b3 ... b7] // serialize model to engine file" << std::endl; + std::cerr << "./efficientnet -d [.engine] [b0 b1 b2 b3 ... b7] // deserialize engine file and run inference" << std::endl; + return -1; + } + GlobalParams global_params = global_params_map[backbone]; + // create a model using the API directly and serialize it to a stream + if (!wtsPath.empty()) + { + IHostMemory *modelStream{nullptr}; + APIToModel(MAX_BATCH_SIZE, &modelStream, wtsPath, block_args_list, global_params); + assert(modelStream != nullptr); + + std::ofstream p(engine_name, 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; + } + + char *trtModelStream{nullptr}; + size_t size{0}; + + std::ifstream file(engine_name, 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 + { + std::cerr << "could not open plan file" << std::endl; + return -1; + } + + // dummy input + float *data = new float[3 * global_params.input_h * global_params.input_w]; + for (int i = 0; i < 3 * global_params.input_h * global_params.input_w; i++) + data[i] = 0.1; + + 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 + float *prob = new float[global_params.num_classes]; + for (int i = 0; i < 100; i++) + { + auto start = std::chrono::system_clock::now(); + doInference(*context, data, prob, 1, global_params); + auto end = std::chrono::system_clock::now(); + std::cout << std::chrono::duration_cast(end - start).count() << "ms" << std::endl; + } + for (unsigned int i = 0; i < 20; i++) + { + std::cout << prob[i] << ", "; + } + std::cout << std::endl; + // Destroy the engine + context->destroy(); + engine->destroy(); + runtime->destroy(); + delete data; + delete prob; + + return 0; +} diff --git a/efficientnet/gen_wts.py b/efficientnet/gen_wts.py new file mode 100644 index 0000000..504dc9c --- /dev/null +++ b/efficientnet/gen_wts.py @@ -0,0 +1,16 @@ +import torch +import struct +from efficientnet_pytorch import EfficientNet +model = EfficientNet.from_pretrained('efficientnet-b3') + +model.eval() +f = open('efficientnet-b3.wts', 'w') +f.write('{}\n'.format(len(model.state_dict().keys()))) +for k, v in model.state_dict().items(): + vr = v.reshape(-1).cpu().numpy() + f.write('{} {} '.format(k, len(vr))) + for vv in vr: + f.write(' ') + f.write(struct.pack('>f',float(vv)).hex()) + f.write('\n') +f.close() diff --git a/efficientnet/logging.h b/efficientnet/logging.h new file mode 100644 index 0000000..602b69f --- /dev/null +++ b/efficientnet/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/efficientnet/utils.hpp b/efficientnet/utils.hpp new file mode 100644 index 0000000..dfbe41b --- /dev/null +++ b/efficientnet/utils.hpp @@ -0,0 +1,251 @@ +#include "NvInfer.h" +#include "cuda_runtime_api.h" +#include "logging.h" +#include +#include +#include +using namespace nvinfer1; + +#define CHECK(status) \ + do \ + { \ + auto ret = (status); \ + if (ret != 0) \ + { \ + std::cerr << "Cuda failure: " << ret << std::endl; \ + abort(); \ + } \ + } while (0) + +// 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; +} + +struct BlockArgs +{ + int num_repeat; + int kernel_size; + int stride; + float expand_ratio; + int input_filters; + int output_filters; + float se_ratio; + bool id_skip; +}; + +struct GlobalParams +{ + int input_h; + int input_w; + int num_classes; + float batch_norm_epsilon; + float width_coefficient; + float depth_coefficient; + int depth_divisor; + int min_depth; +}; + +int roundFilters(int filters, GlobalParams global_params) +{ + float multiplier = global_params.width_coefficient; + int divisor = global_params.depth_divisor; + int min_depth = global_params.min_depth; + filters = int(filters * multiplier); + if (min_depth < 0) + { + min_depth = divisor; + } + // follow the formula transferred from official TensorFlow implementation + int new_filters = std::max(min_depth, int(int(filters + divisor / 2) / divisor) * divisor); + if (new_filters < 0.9 * filters) // prevent rounding by more than 10% + new_filters += divisor; + return int(new_filters); +} + +DimsHW calculateOutputImageSize(DimsHW image_size, int stride) +{ + int image_h = int(ceil(float(image_size.h()) / float(stride))); + int image_w = int(ceil(float(image_size.w()) / float(stride))); + return DimsHW{image_h, image_w}; +} + +int roundRepeats(int repeats, GlobalParams global_params) +{ + float multiplier = global_params.depth_coefficient; + // follow the formula transferred from official TensorFlow implementation + int new_repeats = int(ceil(multiplier * repeats)); + return new_repeats; +} + +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; +} + +IConvolutionLayer *addSamePaddingConv2d(INetworkDefinition *network, std::map &weightMap, ITensor &input, int outch, int kernel_size, int stride, int dilation, int groups, DimsHW image_size, std::string lname, bool bias = true) +{ + int ih = image_size.h(); + int iw = image_size.w(); + int kh = kernel_size; + int kw = kernel_size; + int sh = stride; + int sw = stride; + int oh = ceil(float(ih) / float(sh)); + int ow = ceil(float(iw) / float(sw)); + int pad_h = std::max((oh - 1) * stride + (kh - 1) * dilation + 1 - ih, 0); + int pad_w = std::max((ow - 1) * stride + (kw - 1) * dilation + 1 - iw, 0); + int pad_left = 0; + int pad_right = 0; + int pad_top = 0; + int pad_bottom = 0; + if (pad_h > 0 || pad_w > 0) + { + pad_left = int(pad_w / 2); + pad_right = pad_w - int(pad_w / 2); + pad_top = int(pad_h / 2); + pad_bottom = pad_h - int(pad_h / 2); + } + Weights bias_wt{DataType::kFLOAT, nullptr, 0}; + if (bias) + { + bias_wt = weightMap[lname + ".bias"]; + } + IConvolutionLayer *conv = network->addConvolutionNd(input, outch, DimsHW{kh, kw}, weightMap[lname + ".weight"], bias_wt); + conv->setPrePadding(DimsHW{pad_top, pad_left}); + conv->setPostPadding(DimsHW{pad_bottom, pad_right}); + conv->setStrideNd(DimsHW{stride, stride}); + conv->setDilationNd(DimsHW{dilation, dilation}); + conv->setNbGroups(groups); + return conv; +} + +ILayer *addSwish(INetworkDefinition *network, ITensor &input) +{ + //swish + auto *sigmoid = network->addActivation(input, ActivationType::kSIGMOID); + auto *ew = network->addElementWise(input, *sigmoid->getOutput(0), ElementWiseOperation::kPROD); + return ew; +} + +ITensor *MBConvBlock(INetworkDefinition *network, std::map &weightMap, ITensor &input, std::string lname, BlockArgs block_args, GlobalParams global_params, DimsHW image_size) +{ + bool has_se = block_args.se_ratio > 0 && block_args.se_ratio <= 1; + bool id_skip = block_args.id_skip; + float bn_eps = global_params.batch_norm_epsilon; + int input_filters = block_args.input_filters; + int output_filters = block_args.output_filters; + Weights emptywts{DataType::kFLOAT, nullptr, 0}; + ITensor *x = &input; + int inp = block_args.input_filters; + int oup = int(block_args.input_filters * block_args.expand_ratio); + // expand_ratio != 1 + if (fabs(block_args.expand_ratio - 1) > 1e-5) + { + auto expand_conv = addSamePaddingConv2d(network, weightMap, input, oup, 1, 1, 1, 1, image_size, lname + "._expand_conv"); + auto bn0 = addBatchNorm2d(network, weightMap, *expand_conv->getOutput(0), lname + "._bn0", bn_eps); + auto swish0 = addSwish(network, *bn0->getOutput(0)); + x = swish0->getOutput(0); + } + int k = block_args.kernel_size; + int s = block_args.stride; + auto depthwise_conv = addSamePaddingConv2d(network, weightMap, *x, oup, k, s, 1, oup, image_size, lname + "._depthwise_conv", false); + auto bn1 = addBatchNorm2d(network, weightMap, *depthwise_conv->getOutput(0), lname + "._bn1", bn_eps); + //swish + auto swish1 = addSwish(network, *bn1->getOutput(0)); + x = swish1->getOutput(0); + image_size = calculateOutputImageSize(image_size, s); + if (has_se) + { + auto avg_pool = network->addPoolingNd(*x, PoolingType::kAVERAGE, image_size); + int num_squeezed_channels = std::max(1, int(input_filters * block_args.se_ratio)); + auto se_reduce = addSamePaddingConv2d(network, weightMap, *avg_pool->getOutput(0), num_squeezed_channels, 1, 1, 1, 1, DimsHW{1, 1}, lname + "._se_reduce"); + + auto swish2 = addSwish(network, *se_reduce->getOutput(0)); + auto se_expand = addSamePaddingConv2d(network, weightMap, *swish2->getOutput(0), oup, 1, 1, 1, 1, DimsHW{1, 1}, lname + "._se_expand"); + + auto *sigmoid = network->addActivation(*se_expand->getOutput(0), ActivationType::kSIGMOID); + auto *ew = network->addElementWise(*x, *sigmoid->getOutput(0), ElementWiseOperation::kPROD); + x = ew->getOutput(0); + } + int final_oup = block_args.output_filters; + auto project_conv = addSamePaddingConv2d(network, weightMap, *x, final_oup, 1, 1, 1, 1, image_size, lname + "._project_conv"); + + auto bn2 = addBatchNorm2d(network, weightMap, *project_conv->getOutput(0), lname + "._bn2", bn_eps); + x = bn2->getOutput(0); + + if (id_skip && block_args.stride == 1 && input_filters == output_filters) + { + auto *ew = network->addElementWise(input, *x, ElementWiseOperation::kSUM); + x = ew->getOutput(0); + } + return x; +}