From 004e2d5a5b59bfd45038838876e9dd9ba4985a5d Mon Sep 17 00:00:00 2001 From: wang-xinyu Date: Wed, 1 Apr 2020 21:19:57 +0800 Subject: [PATCH] add retinaface, unfinished --- retinaface/CMakeLists.txt | 34 +++ retinaface/common.h | 356 ++++++++++++++++++++++++++++ retinaface/retina_r50.cpp | 483 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 873 insertions(+) create mode 100644 retinaface/CMakeLists.txt create mode 100644 retinaface/common.h create mode 100644 retinaface/retina_r50.cpp diff --git a/retinaface/CMakeLists.txt b/retinaface/CMakeLists.txt new file mode 100644 index 0000000..685c804 --- /dev/null +++ b/retinaface/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 2.6) + +project(retinaface) + +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) + +set(CUDA_NVCC_PLAGS ${CUDA_NVCC_PLAGS};-std=c++11;-g;-G;-gencode;arch=compute_30;code=sm_30) + +include_directories(${PROJECT_SOURCE_DIR}/include) +include_directories(/usr/local/cuda-9.0/targets/aarch64-linux/include) +link_directories(/usr/local/cuda-9.0/targets/aarch64-linux/lib) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Ofast -Wfatal-errors -D_MWAITXINTRIN_H_INCLUDED") + +#cuda_add_library(leaky ${PROJECT_SOURCE_DIR}/leaky.cu) +#cuda_add_library(yololayer ${PROJECT_SOURCE_DIR}/yololayer.cu) + +find_package(OpenCV) +include_directories(OpenCV_INCLUDE_DIRS) + +add_executable(retina_50 ${PROJECT_SOURCE_DIR}/retina_r50.cpp) +target_link_libraries(retina_50 nvinfer nvinfer_plugin) +target_link_libraries(retina_50 cudart) +#target_link_libraries(retina yololayer) +target_link_libraries(retina_50 ${OpenCV_LIBRARIES}) + +add_definitions(-O2 -pthread) + diff --git a/retinaface/common.h b/retinaface/common.h new file mode 100644 index 0000000..3b9c30c --- /dev/null +++ b/retinaface/common.h @@ -0,0 +1,356 @@ +#ifndef _TRT_COMMON_H_ +#define _TRT_COMMON_H_ +#include "NvInfer.h" +#include "NvOnnxConfig.h" +#include "NvOnnxParser.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define CHECK(status) \ + do \ + { \ + auto ret = (status); \ + if (ret != 0) \ + { \ + std::cout << "Cuda failure: " << ret; \ + abort(); \ + } \ + } while (0) + +constexpr long double operator"" _GB(long double val) { return val * (1 << 30); } +constexpr long double operator"" _MB(long double val) { return val * (1 << 20); } +constexpr long double operator"" _KB(long double val) { return val * (1 << 10); } + +// These is necessary if we want to be able to write 1_GB instead of 1.0_GB. +// Since the return type is signed, -1_GB will work as expected. +constexpr long long int operator"" _GB(long long unsigned int val) { return val * (1 << 30); } +constexpr long long int operator"" _MB(long long unsigned int val) { return val * (1 << 20); } +constexpr long long int operator"" _KB(long long unsigned int val) { return val * (1 << 10); } + +// Logger for TensorRT info/warning/errors +class Logger : public nvinfer1::ILogger +{ +public: + + Logger(): Logger(Severity::kWARNING) {} + + Logger(Severity severity): reportableSeverity(severity) {} + + void log(Severity severity, const char* msg) override + { + // suppress messages with severity enum value greater than the reportable + if (severity > reportableSeverity) return; + + switch (severity) + { + case Severity::kINTERNAL_ERROR: std::cerr << "INTERNAL_ERROR: "; break; + case Severity::kERROR: std::cerr << "ERROR: "; break; + case Severity::kWARNING: std::cerr << "WARNING: "; break; + case Severity::kINFO: std::cerr << "INFO: "; break; + default: std::cerr << "UNKNOWN: "; break; + } + std::cerr << msg << std::endl; + } + + Severity reportableSeverity{Severity::kWARNING}; +}; + +// Locate path to file, given its filename or filepath suffix and possible dirs it might lie in +// Function will also walk back MAX_DEPTH dirs from CWD to check for such a file path +inline std::string locateFile(const std::string& filepathSuffix, const std::vector& directories) +{ + const int MAX_DEPTH{10}; + bool found{false}; + std::string filepath; + + for (auto& dir : directories) + { + filepath = dir + filepathSuffix; + + for (int i = 0; i < MAX_DEPTH && !found; i++) + { + std::ifstream checkFile(filepath); + found = checkFile.is_open(); + if (found) break; + filepath = "../" + filepath; // Try again in parent dir + } + + if (found) + { + break; + } + + filepath.clear(); + } + + if (filepath.empty()) { + std::string directoryList = std::accumulate(directories.begin() + 1, directories.end(), directories.front(), + [](const std::string& a, const std::string& b) { return a + "\n\t" + b; }); + throw std::runtime_error("Could not find " + filepathSuffix + " in data directories:\n\t" + directoryList); + } + return filepath; +} + +inline void readPGMFile(const std::string& fileName, uint8_t* buffer, int inH, int inW) +{ + std::ifstream infile(fileName, std::ifstream::binary); + assert(infile.is_open() && "Attempting to read from a file that is not open."); + std::string magic, h, w, max; + infile >> magic >> h >> w >> max; + infile.seekg(1, infile.cur); + infile.read(reinterpret_cast(buffer), inH * inW); +} + +namespace samples_common +{ + +inline void* safeCudaMalloc(size_t memSize) +{ + void* deviceMem; + CHECK(cudaMalloc(&deviceMem, memSize)); + if (deviceMem == nullptr) + { + std::cerr << "Out of memory" << std::endl; + exit(1); + } + return deviceMem; +} + +inline bool isDebug() +{ + return (std::getenv("TENSORRT_DEBUG") ? true : false); +} + +struct InferDeleter +{ + template + void operator()(T* obj) const + { + if (obj) { + obj->destroy(); + } + } +}; + +template +inline std::shared_ptr infer_object(T* obj) +{ + if (!obj) { + throw std::runtime_error("Failed to create object"); + } + return std::shared_ptr(obj, InferDeleter()); +} + +template +inline std::vector argsort(Iter begin, Iter end, bool reverse = false) +{ + std::vector inds(end - begin); + std::iota(inds.begin(), inds.end(), 0); + if (reverse) { + std::sort(inds.begin(), inds.end(), [&begin](size_t i1, size_t i2) { + return begin[i2] < begin[i1]; + }); + } + else + { + std::sort(inds.begin(), inds.end(), [&begin](size_t i1, size_t i2) { + return begin[i1] < begin[i2]; + }); + } + return inds; +} + +inline bool readReferenceFile(const std::string& fileName, std::vector& refVector) +{ + std::ifstream infile(fileName); + if (!infile.is_open()) { + cout << "ERROR: readReferenceFile: Attempting to read from a file that is not open." << endl; + return false; + } + std::string line; + while (std::getline(infile, line)) { + if (line.empty()) continue; + refVector.push_back(line); + } + infile.close(); + return true; +} + +template +inline std::vector classify(const vector& refVector, const result_vector_t& output, const size_t topK) +{ + auto inds = samples_common::argsort(output.cbegin(), output.cend(), true); + std::vector result; + for (size_t k = 0; k < topK; ++k) { + result.push_back(refVector[inds[k]]); + } + return result; +} + +//...LG returns top K indices, not values. +template +inline vector topK(const vector inp, const size_t k) +{ + vector result; + std::vector inds = samples_common::argsort(inp.cbegin(), inp.cend(), true); + result.assign(inds.begin(), inds.begin()+k); + return result; +} + +template +inline bool readASCIIFile(const string& fileName, const size_t size, vector& out) +{ + std::ifstream infile(fileName); + if (!infile.is_open()) { + cout << "ERROR readASCIIFile: Attempting to read from a file that is not open." << endl; + return false; + } + out.clear(); + out.reserve(size); + out.assign(std::istream_iterator(infile), std::istream_iterator()); + infile.close(); + return true; +} + +template +inline bool writeASCIIFile(const string& fileName, const vector& in) +{ + std::ofstream outfile(fileName); + if (!outfile.is_open()) { + cout << "ERROR: writeASCIIFile: Attempting to write to a file that is not open." << endl; + return false; + } + for (auto fn : in) { + outfile << fn << " "; + } + outfile.close(); + return true; +} + +inline void print_version() +{ +//... This can be only done after statically linking this support into parserONNX.library +#if 0 + std::cout << "Parser built against:" << std::endl; + std::cout << " ONNX IR version: " << nvonnxparser::onnx_ir_version_string(onnx::IR_VERSION) << std::endl; +#endif + std::cout << " TensorRT version: " + << NV_TENSORRT_MAJOR << "." + << NV_TENSORRT_MINOR << "." + << NV_TENSORRT_PATCH << "." + << NV_TENSORRT_BUILD << std::endl; +} + +inline string getFileType(const string& filepath) +{ + return filepath.substr(filepath.find_last_of(".") + 1); +} + +inline string toLower(const string& inp) +{ + string out = inp; + std::transform(out.begin(), out.end(), out.begin(), ::tolower); + return out; +} + +inline unsigned int getElementSize(nvinfer1::DataType t) +{ + switch (t) + { + case nvinfer1::DataType::kINT32: return 4; + case nvinfer1::DataType::kFLOAT: return 4; + case nvinfer1::DataType::kHALF: return 2; + case nvinfer1::DataType::kINT8: return 1; + } + throw std::runtime_error("Invalid DataType."); + return 0; +} + +inline int64_t volume(const nvinfer1::Dims& d) +{ + return std::accumulate(d.d, d.d + d.nbDims, 1, std::multiplies()); +} + +// Struct to maintain command-line arguments. +struct Args +{ + bool runInInt8 = false; +}; + +// Populates the Args struct with the provided command-line parameters. +inline void parseArgs(Args& args, int argc, char* argv[]) +{ + if (argc >= 1) + { + for (int i = 1; i < argc; ++i) + { + if (!strcmp(argv[i], "--int8")) args.runInInt8 = true; + } + } +} + +template +struct PPM +{ + std::string magic, fileName; + int h, w, max; + uint8_t buffer[C * H * W]; +}; + +struct BBox +{ + float x1, y1, x2, y2; +}; + +template +inline void writePPMFileWithBBox(const std::string& filename, PPM& ppm, const BBox& bbox) +{ + std::ofstream outfile("./" + filename, std::ofstream::binary); + assert(!outfile.fail()); + outfile << "P6" << "\n" << ppm.w << " " << ppm.h << "\n" << ppm.max << "\n"; + auto round = [](float x) -> int { return int(std::floor(x + 0.5f)); }; + const int x1 = std::min(std::max(0, round(int(bbox.x1))), W - 1); + const int x2 = std::min(std::max(0, round(int(bbox.x2))), W - 1); + const int y1 = std::min(std::max(0, round(int(bbox.y1))), H - 1); + const int y2 = std::min(std::max(0, round(int(bbox.y2))), H - 1); + for (int x = x1; x <= x2; ++x) + { + // bbox top border + ppm.buffer[(y1 * ppm.w + x) * 3] = 255; + ppm.buffer[(y1 * ppm.w + x) * 3 + 1] = 0; + ppm.buffer[(y1 * ppm.w + x) * 3 + 2] = 0; + // bbox bottom border + ppm.buffer[(y2 * ppm.w + x) * 3] = 255; + ppm.buffer[(y2 * ppm.w + x) * 3 + 1] = 0; + ppm.buffer[(y2 * ppm.w + x) * 3 + 2] = 0; + } + for (int y = y1; y <= y2; ++y) + { + // bbox left border + ppm.buffer[(y * ppm.w + x1) * 3] = 255; + ppm.buffer[(y * ppm.w + x1) * 3 + 1] = 0; + ppm.buffer[(y * ppm.w + x1) * 3 + 2] = 0; + // bbox right border + ppm.buffer[(y * ppm.w + x2) * 3] = 255; + ppm.buffer[(y * ppm.w + x2) * 3 + 1] = 0; + ppm.buffer[(y * ppm.w + x2) * 3 + 2] = 0; + } + outfile.write(reinterpret_cast(ppm.buffer), ppm.w * ppm.h * 3); +} + +} // namespace samples_common + +#endif // _TRT_COMMON_H_ diff --git a/retinaface/retina_r50.cpp b/retinaface/retina_r50.cpp new file mode 100644 index 0000000..a419b3a --- /dev/null +++ b/retinaface/retina_r50.cpp @@ -0,0 +1,483 @@ +#include "NvInfer.h" +#include "NvInferPlugin.h" +#include "cuda_runtime_api.h" +#include "common.h" +#include +#include +#include +#include +#include +#include +//#include "plugin_factory.h" +//#include "yololayer.h" +#include + +#define USE_FP16 // comment out this if want to use FP32 + +// stuff we know about the network and the input/output blobs +static const int INPUT_H = 360; +static const int INPUT_W = 640; +static const int OUTPUT_SIZE = 2048 * 12 * 20; + +const char* INPUT_BLOB_NAME = "data"; +const char* OUTPUT_BLOB_NAME = "prob"; + +using namespace nvinfer1; + +static Logger gLogger; + +typedef struct { + float bbox[4]; + float det_confidence; + float class_id; + float class_confidence; +} Detection; + +cv::Mat preprocess_img(cv::Mat& img, int input_dim) { + int w, h, x, y; + if (img.cols > img.rows) { + w = input_dim; + h = input_dim * img.rows / img.cols; + x = 0; + y = (input_dim - h) / 2; + } else { + w = input_dim * img.cols / img.rows; + h = input_dim; + x = (input_dim - w) / 2; + y = 0; + } + cv::Mat re(h, w, CV_8UC3); + cv::resize(img, re, re.size(), 0, 0, cv::INTER_CUBIC); + cv::Mat out(input_dim, input_dim, CV_8UC3, cv::Scalar(128, 128, 128)); + re.copyTo(out(cv::Rect(x, y, re.cols, re.rows))); + return out; +} + +cv::Rect get_rect(cv::Mat& img, int input_dim, float bbox[4]) { + int l, r, t, b; + if (img.cols > img.rows) { + l = bbox[0] - bbox[2]/2.f; + r = bbox[0] + bbox[2]/2.f; + t = bbox[1] - bbox[3]/2.f - (input_dim - input_dim * img.rows / img.cols) / 2; + b = bbox[1] + bbox[3]/2.f - (input_dim - input_dim * img.rows / img.cols) / 2; + l = l * img.cols / input_dim; + r = r * img.cols / input_dim; + t = t * img.cols / input_dim; + b = b * img.cols / input_dim; + } else { + l = bbox[0] - bbox[2]/2.f - (input_dim - input_dim * img.cols / img.rows) / 2; + r = bbox[0] + bbox[2]/2.f - (input_dim - input_dim * img.cols / img.rows) / 2; + t = bbox[1] - bbox[3]/2.f; + b = bbox[1] + bbox[3]/2.f; + l = l * img.rows / input_dim; + r = r * img.rows / input_dim; + t = t * img.rows / input_dim; + b = b * img.rows / input_dim; + } + return cv::Rect(l, t, r-l, b-t); +} + +float iou(float lbox[4], float rbox[4]) { + float interBox[] = { + max(lbox[0] - lbox[2]/2.f , rbox[0] - rbox[2]/2.f), //left + min(lbox[0] + lbox[2]/2.f , rbox[0] + rbox[2]/2.f), //right + max(lbox[1] - lbox[3]/2.f , rbox[1] - rbox[3]/2.f), //top + min(lbox[1] + lbox[3]/2.f , rbox[1] + rbox[3]/2.f), //bottom + }; + + if(interBox[2] > interBox[3] || interBox[0] > interBox[1]) + return 0.0f; + + float interBoxS =(interBox[1]-interBox[0])*(interBox[3]-interBox[2]); + return interBoxS/(lbox[2]*lbox[3] + rbox[2]*rbox[3] -interBoxS); +} + +bool cmp(Detection& a, Detection& b) { + return a.det_confidence > b.det_confidence; +} + +void nms(std::vector& res, float *output, float nms_thresh = 0.4) { + std::map> m; + for (int i = 0; i < OUTPUT_SIZE / 7; i++) { + if (output[7 * i + 4] <= 0.5) continue; + Detection det; + memcpy(&det, &output[7 * i], 7 * sizeof(float)); + if (m.count(det.class_id) == 0) m.emplace(det.class_id, std::vector()); + m[det.class_id].push_back(det); + } + for (auto it = m.begin(); it != m.end(); it++) { + //std::cout << it->second[0].class_id << " --- " << std::endl; + auto& dets = it->second; + std::sort(dets.begin(), dets.end(), cmp); + for (size_t m = 0; m < dets.size(); ++m) { + auto& item = dets[m]; + res.push_back(item); + for (size_t n = m + 1; n < dets.size(); ++n) { + if (iou(item.bbox, dets[n].bbox) > nms_thresh) { + dets.erase(dets.begin()+n); + --n; + } + } + } + } +} + +// 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; +} + +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; + std::cout << "len " << len << std::endl; + + 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) { + Weights emptywts{DataType::kFLOAT, nullptr, 0}; + + IConvolutionLayer* conv1 = network->addConvolution(input, outch, DimsHW{1, 1}, weightMap[lname + "conv1.weight"], emptywts); + assert(conv1); + + 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 { 1, 1, 32, 32 } with name INPUT_BLOB_NAME + ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{3, INPUT_H, INPUT_W}); + assert(data); + + std::map weightMap = loadWeights("../retinaface.wts"); + Weights emptywts{DataType::kFLOAT, nullptr, 0}; + + // ------------- backbone resnet50 --------------- + IConvolutionLayer* conv1 = network->addConvolution(*data, 64, DimsHW{7, 7}, weightMap["body.conv1.weight"], emptywts); + assert(conv1); + conv1->setStride(DimsHW{2, 2}); + conv1->setPadding(DimsHW{3, 3}); + + IScaleLayer* bn1 = addBatchNorm2d(network, weightMap, *conv1->getOutput(0), "body.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}); + + IActivationLayer* x = bottleneck(network, weightMap, *pool1->getOutput(0), 64, 64, 1, "body.layer1.0."); + x = bottleneck(network, weightMap, *x->getOutput(0), 256, 64, 1, "body.layer1.1."); + x = bottleneck(network, weightMap, *x->getOutput(0), 256, 64, 1, "body.layer1.2."); + + x = bottleneck(network, weightMap, *x->getOutput(0), 256, 128, 2, "body.layer2.0."); + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 128, 1, "body.layer2.1."); + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 128, 1, "body.layer2.2."); + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 128, 1, "body.layer2.3."); + IActivationLayer* layer2 = x; + + x = bottleneck(network, weightMap, *x->getOutput(0), 512, 256, 2, "body.layer3.0."); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "body.layer3.1."); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "body.layer3.2."); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "body.layer3.3."); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "body.layer3.4."); + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 256, 1, "body.layer3.5."); + IActivationLayer* layer3 = x; + + x = bottleneck(network, weightMap, *x->getOutput(0), 1024, 512, 2, "body.layer4.0."); + x = bottleneck(network, weightMap, *x->getOutput(0), 2048, 512, 1, "body.layer4.1."); + x = bottleneck(network, weightMap, *x->getOutput(0), 2048, 512, 1, "body.layer4.2."); + IActivationLayer* layer4 = x; + + //IPoolingLayer* pool2 = network->addPooling(*x->getOutput(0), PoolingType::kAVERAGE, DimsHW{7, 7}); + //assert(pool2); + //pool2->setStride(DimsHW{1, 1}); + // + //IFullyConnectedLayer* fc1 = network->addFullyConnected(*pool2->getOutput(0), 1000, weightMap["fc.weight"], weightMap["fc.bias"]); + //assert(fc1); + + layer4->getOutput(0)->setName(OUTPUT_BLOB_NAME); + std::cout << "set name out" << std::endl; + network->markOutput(*layer4->getOutput(0)); + + // Build engine + builder->setMaxBatchSize(maxBatchSize); + builder->setMaxWorkspaceSize(1 << 20); +#ifdef USE_FP16 + builder->setFp16Mode(true); +#endif + ICudaEngine* engine = builder->buildCudaEngine(*network); + std::cout << "build out" << 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) +{ + // 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 * 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 * 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) +{ + std::cout << "beginning" << std::endl; + if (argc != 2) { + std::cerr << "arguments not right!" << std::endl; + std::cerr << "./retina_r50 -s // serialize model to plan file" << std::endl; + std::cerr << "./retina_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("retina_r50.engine"); + 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("retina_r50.engine", 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; + } + + // prepare input data --------------------------- + float data[3 * INPUT_H * INPUT_W]; + for (int i = 0; i < 3 * INPUT_H * INPUT_W; i++) + data[i] = 1.0; + + //cv::Mat img = cv::imread("../dog.jpg"); + //cv::Mat pr_img = preprocess_img(img, INPUT_H); + //cv::imwrite("123.jpg", pr_img); + //for (int i = 0; i < INPUT_H * INPUT_W; i++) { + // data[i] = pr_img.at(i)[2] / 255.0; + // data[i + INPUT_H * INPUT_W] = pr_img.at(i)[1] / 255.0; + // data[i + 2 * INPUT_H * INPUT_W] = pr_img.at(i)[0] / 255.0; + //} + + //PluginFactory pf; + IRuntime* runtime = createInferRuntime(gLogger); + assert(runtime != nullptr); + //ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size, &pf); + ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size, nullptr); + assert(engine != nullptr); + IExecutionContext* context = engine->createExecutionContext(); + assert(context != nullptr); + + // Run inference + static float prob[OUTPUT_SIZE]; + for (int i = 0; i < 10; i++) { + auto start = std::chrono::system_clock::now(); + doInference(*context, data, prob, 1); + //std::vector res; + //nms(res, prob); + //for (size_t j = 0; j < res.size(); j++) { + // float *p = (float*)&res[j]; + // for (size_t k = 0; k < 7; k++) { + // std::cout << p[k] << ", "; + // } + // std::cout << std::endl; + // cv::Rect r = get_rect(img, INPUT_W, res[j].bbox); + // cv::rectangle(img, r, cv::Scalar(0x27, 0xC1, 0x36), 2); + // cv::putText(img, std::to_string((int)res[j].class_id), cv::Point(r.x, r.y - 1), cv::FONT_HERSHEY_PLAIN, 1.2, cv::Scalar(0xFF, 0xFF, 0xFF), 2); + //} + auto end = std::chrono::system_clock::now(); + std::cout << std::chrono::duration_cast(end - start).count() << "ms" << std::endl; + //cv::imwrite("res.jpg", img); + } + + // 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 < OUTPUT_SIZE; i++) + { + std::cout << prob[i] << ", "; + if (i % 10 == 0) std::cout << i / 10 << std::endl; + } + std::cout << std::endl; + + return 0; +}