add crnn
This commit is contained in:
parent
438b46e0dd
commit
06ac8cd71d
@ -10,6 +10,7 @@ All the models are implemented in pytorch or mxnet first, and export a weights f
|
|||||||
|
|
||||||
## News
|
## News
|
||||||
|
|
||||||
|
- `13 Sep 2020`. Add crnn, and got 1000fps on GTX1080.
|
||||||
- `7 Sep 2020`. Implement retinaface(mobilenet0.25), and got 333fps on GTX1080.
|
- `7 Sep 2020`. Implement retinaface(mobilenet0.25), and got 333fps on GTX1080.
|
||||||
- `28 Aug 2020`. [BaofengZan](https://github.com/BaofengZan) added a tutorial for compiling and running tensorrtx on windows.
|
- `28 Aug 2020`. [BaofengZan](https://github.com/BaofengZan) added a tutorial for compiling and running tensorrtx on windows.
|
||||||
- `16 Aug 2020`. [upczww](https://github.com/upczww) added a python wrapper for yolov5.
|
- `16 Aug 2020`. [upczww](https://github.com/upczww) added a python wrapper for yolov5.
|
||||||
@ -64,6 +65,7 @@ Following models are implemented.
|
|||||||
|[arcface](./arcface)| LResNet50E-IR, weights from [deepinsight/insightface](https://github.com/deepinsight/insightface) |
|
|[arcface](./arcface)| LResNet50E-IR, weights from [deepinsight/insightface](https://github.com/deepinsight/insightface) |
|
||||||
|[retinafaceAntiCov](./retinafaceAntiCov)| mobilenet0.25, weights from [deepinsight/insightface](https://github.com/deepinsight/insightface), retinaface anti-COVID-19, detect face and mask attribute |
|
|[retinafaceAntiCov](./retinafaceAntiCov)| mobilenet0.25, weights from [deepinsight/insightface](https://github.com/deepinsight/insightface), retinaface anti-COVID-19, detect face and mask attribute |
|
||||||
|[dbnet](./dbnet)| Scene Text Detection, weights from [BaofengZan/DBNet.pytorch](https://github.com/BaofengZan/DBNet.pytorch) |
|
|[dbnet](./dbnet)| Scene Text Detection, weights from [BaofengZan/DBNet.pytorch](https://github.com/BaofengZan/DBNet.pytorch) |
|
||||||
|
|[crnn](./crnn)| pytorch implementation from [meijieru/crnn.pytorch](https://github.com/meijieru/crnn.pytorch) |
|
||||||
|
|
||||||
## Tricky Operations
|
## Tricky Operations
|
||||||
|
|
||||||
@ -87,6 +89,7 @@ Some tricky operations encountered in these models, already solved, but might ha
|
|||||||
|mish| mish activation is implemented as a plugin, mish is used in yolov4 |
|
|mish| mish activation is implemented as a plugin, mish is used in yolov4 |
|
||||||
|prelu| mxnet's prelu activation with trainable gamma is implemented as a plugin, used in arcface |
|
|prelu| mxnet's prelu activation with trainable gamma is implemented as a plugin, used in arcface |
|
||||||
|HardSwish| hard_swish = x * hard_sigmoid, used in yolov5 v3.0 |
|
|HardSwish| hard_swish = x * hard_sigmoid, used in yolov5 v3.0 |
|
||||||
|
|LSTM| Implemented pytorch nn.LSTM() with tensorrt api |
|
||||||
|
|
||||||
## Speed Benchmark
|
## Speed Benchmark
|
||||||
|
|
||||||
@ -107,6 +110,7 @@ Some tricky operations encountered in these models, already solved, but might ha
|
|||||||
| RetinaFace(resnet50) | Xeon E5-2620/GTX1080 | 1 | FP32 | 480x640 | 90 |
|
| RetinaFace(resnet50) | Xeon E5-2620/GTX1080 | 1 | FP32 | 480x640 | 90 |
|
||||||
| RetinaFace(mobilenet0.25) | Xeon E5-2620/GTX1080 | 1 | FP32 | 480x640 | 333 |
|
| RetinaFace(mobilenet0.25) | Xeon E5-2620/GTX1080 | 1 | FP32 | 480x640 | 333 |
|
||||||
| ArcFace(LResNet50E-IR) | Xeon E5-2620/GTX1080 | 1 | FP32 | 112x112 | 333 |
|
| ArcFace(LResNet50E-IR) | Xeon E5-2620/GTX1080 | 1 | FP32 | 112x112 | 333 |
|
||||||
|
| CRNN | Xeon E5-2620/GTX1080 | 1 | FP32 | 32x100 | 1000 |
|
||||||
|
|
||||||
Help wanted, if you got speed results, please add an issue or PR.
|
Help wanted, if you got speed results, please add an issue or PR.
|
||||||
|
|
||||||
|
|||||||
33
crnn/CMakeLists.txt
Normal file
33
crnn/CMakeLists.txt
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
cmake_minimum_required(VERSION 2.6)
|
||||||
|
|
||||||
|
project(crnn)
|
||||||
|
|
||||||
|
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)
|
||||||
|
if (CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64")
|
||||||
|
message("embed_platform on")
|
||||||
|
include_directories(/usr/local/cuda/targets/aarch64-linux/include)
|
||||||
|
link_directories(/usr/local/cuda/targets/aarch64-linux/lib)
|
||||||
|
else()
|
||||||
|
message("embed_platform off")
|
||||||
|
include_directories(/usr/local/cuda/include)
|
||||||
|
link_directories(/usr/local/cuda/lib64)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
find_package(OpenCV)
|
||||||
|
include_directories(OpenCV_INCLUDE_DIRS)
|
||||||
|
|
||||||
|
add_executable(crnn ${PROJECT_SOURCE_DIR}/crnn.cpp)
|
||||||
|
target_link_libraries(crnn nvinfer)
|
||||||
|
target_link_libraries(crnn cudart)
|
||||||
|
target_link_libraries(crnn ${OpenCV_LIBS})
|
||||||
|
|
||||||
|
add_definitions(-O2 -pthread)
|
||||||
|
|
||||||
44
crnn/README.md
Normal file
44
crnn/README.md
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
# crnn
|
||||||
|
|
||||||
|
The Pytorch implementation is [meijieru/crnn.pytorch](https://github.com/meijieru/crnn.pytorch).
|
||||||
|
|
||||||
|
## How to Run
|
||||||
|
|
||||||
|
```
|
||||||
|
1. generate crnn.wts from pytorch
|
||||||
|
|
||||||
|
git clone https://github.com/wang-xinyu/tensorrtx.git
|
||||||
|
git clone https://github.com/meijieru/crnn.pytorch.git
|
||||||
|
// download its weights 'crnn.pth'
|
||||||
|
// copy tensorrtx/crnn/genwts.py into crnn.pytorch/
|
||||||
|
// go to crnn.pytorch/
|
||||||
|
python genwts.py
|
||||||
|
// a file 'crnn.wts' will be generated.
|
||||||
|
|
||||||
|
2. build tensorrtx/crnn and run
|
||||||
|
|
||||||
|
// put crnn.wts into tensorrtx/crnn
|
||||||
|
// go to tensorrtx/crnn
|
||||||
|
mkdir build
|
||||||
|
cd build
|
||||||
|
cmake ..
|
||||||
|
make
|
||||||
|
sudo ./crnn -s // serialize model to plan file i.e. 'crnn.engine'
|
||||||
|
// copy crnn.pytorch/data/demo.png here
|
||||||
|
sudo ./crnn -d // deserialize plan file and run inference
|
||||||
|
|
||||||
|
3. check the output as follows:
|
||||||
|
|
||||||
|
raw: a-----v--a-i-l-a-bb-l-e---
|
||||||
|
sim: available
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## More Information
|
||||||
|
|
||||||
|
See the readme in [home page.](https://github.com/wang-xinyu/tensorrtx)
|
||||||
|
|
||||||
|
## Acknowledgment
|
||||||
|
|
||||||
|
Thanks for the donation for this crnn tensorrt implementation from @雍.
|
||||||
|
|
||||||
418
crnn/crnn.cpp
Normal file
418
crnn/crnn.cpp
Normal file
@ -0,0 +1,418 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <chrono>
|
||||||
|
#include <map>
|
||||||
|
#include <opencv2/opencv.hpp>
|
||||||
|
#include "NvInfer.h"
|
||||||
|
#include "cuda_runtime_api.h"
|
||||||
|
#include "logging.h"
|
||||||
|
|
||||||
|
#define CHECK(status) \
|
||||||
|
do\
|
||||||
|
{\
|
||||||
|
auto ret = (status);\
|
||||||
|
if (ret != 0)\
|
||||||
|
{\
|
||||||
|
std::cerr << "Cuda failure: " << ret << std::endl;\
|
||||||
|
abort();\
|
||||||
|
}\
|
||||||
|
} while (0)
|
||||||
|
|
||||||
|
#define USE_FP16 // comment out this if want to use FP32
|
||||||
|
#define DEVICE 0 // GPU id
|
||||||
|
#define BATCH_SIZE 1
|
||||||
|
|
||||||
|
// stuff we know about the network and the input/output blobs
|
||||||
|
static const int INPUT_H = 32;
|
||||||
|
static const int INPUT_W = 100;
|
||||||
|
static const int OUTPUT_SIZE = 26 * 37;
|
||||||
|
const char* INPUT_BLOB_NAME = "data";
|
||||||
|
const char* OUTPUT_BLOB_NAME = "prob";
|
||||||
|
static Logger gLogger;
|
||||||
|
|
||||||
|
const int ks[] = {3, 3, 3, 3, 3, 3, 2};
|
||||||
|
const int ps[] = {1, 1, 1, 1, 1, 1, 0};
|
||||||
|
const int ss[] = {1, 1, 1, 1, 1, 1, 1};
|
||||||
|
const int nm[] = {64, 128, 256, 256, 512, 512, 512};
|
||||||
|
const std::string alphabet = "-0123456789abcdefghijklmnopqrstuvwxyz";
|
||||||
|
|
||||||
|
using namespace nvinfer1;
|
||||||
|
|
||||||
|
std::string strDecode(std::vector<int>& preds, bool raw) {
|
||||||
|
std::string str;
|
||||||
|
if (raw) {
|
||||||
|
for (auto v: preds) {
|
||||||
|
str.push_back(alphabet[v]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (size_t i = 0; i < preds.size(); i++) {
|
||||||
|
if (preds[i] == 0 || (i > 0 && preds[i - 1] == preds[i])) continue;
|
||||||
|
str.push_back(alphabet[preds[i]]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TensorRT weight files have a simple space delimited format:
|
||||||
|
// [type] [size] <data x size in hex>
|
||||||
|
std::map<std::string, Weights> loadWeights(const std::string file) {
|
||||||
|
std::cout << "Loading weights: " << file << std::endl;
|
||||||
|
std::map<std::string, Weights> weightMap;
|
||||||
|
|
||||||
|
// Open weights file
|
||||||
|
std::ifstream input(file);
|
||||||
|
assert(input.is_open() && "Unable to load weight file. please check if the .wts file path is right!!!!!!");
|
||||||
|
|
||||||
|
// 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<uint32_t*>(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<std::string, Weights>& 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<float*>(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<float*>(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<float*>(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
ILayer* convRelu(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& input, int i, bool use_bn = false) {
|
||||||
|
int nOut = nm[i];
|
||||||
|
IConvolutionLayer* conv = network->addConvolutionNd(input, nOut, DimsHW{ks[i], ks[i]}, weightMap["cnn.conv" + std::to_string(i) + ".weight"], weightMap["cnn.conv" + std::to_string(i) + ".bias"]);
|
||||||
|
assert(conv);
|
||||||
|
conv->setStrideNd(DimsHW{ss[i], ss[i]});
|
||||||
|
conv->setPaddingNd(DimsHW{ps[i], ps[i]});
|
||||||
|
ILayer *tmp = conv;
|
||||||
|
if (use_bn) {
|
||||||
|
tmp = addBatchNorm2d(network, weightMap, *conv->getOutput(0), "cnn.batchnorm" + std::to_string(i), 1e-5);
|
||||||
|
}
|
||||||
|
auto relu = network->addActivation(*tmp->getOutput(0), ActivationType::kRELU);
|
||||||
|
assert(relu);
|
||||||
|
return relu;
|
||||||
|
}
|
||||||
|
|
||||||
|
void splitLstmWeights(std::map<std::string, Weights>& weightMap, std::string lname) {
|
||||||
|
int weight_size = weightMap[lname].count;
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
Weights wt{DataType::kFLOAT, nullptr, 0};
|
||||||
|
wt.count = weight_size / 4;
|
||||||
|
float *val = reinterpret_cast<float*>(malloc(sizeof(float) * wt.count));
|
||||||
|
memcpy(val, (float*)weightMap[lname].values + wt.count * i, sizeof(float) * wt.count);
|
||||||
|
wt.values = val;
|
||||||
|
weightMap[lname + std::to_string(i)] = wt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ILayer* addLSTM(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& input, int nHidden, std::string lname) {
|
||||||
|
splitLstmWeights(weightMap, lname + ".weight_ih_l0");
|
||||||
|
splitLstmWeights(weightMap, lname + ".weight_hh_l0");
|
||||||
|
splitLstmWeights(weightMap, lname + ".bias_ih_l0");
|
||||||
|
splitLstmWeights(weightMap, lname + ".bias_hh_l0");
|
||||||
|
splitLstmWeights(weightMap, lname + ".weight_ih_l0_reverse");
|
||||||
|
splitLstmWeights(weightMap, lname + ".weight_hh_l0_reverse");
|
||||||
|
splitLstmWeights(weightMap, lname + ".bias_ih_l0_reverse");
|
||||||
|
splitLstmWeights(weightMap, lname + ".bias_hh_l0_reverse");
|
||||||
|
Dims dims = input.getDimensions();
|
||||||
|
std::cout << "lstm input shape: " << dims.nbDims << " [" << dims.d[0] << " " << dims.d[1] << " " << dims.d[2] << "]"<< std::endl;
|
||||||
|
auto lstm = network->addRNNv2(input, 1, nHidden, dims.d[1], RNNOperation::kLSTM);
|
||||||
|
lstm->setDirection(RNNDirection::kBIDIRECTION);
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kINPUT, true, weightMap[lname + ".weight_ih_l00"]);
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kFORGET, true, weightMap[lname + ".weight_ih_l01"]);
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kCELL, true, weightMap[lname + ".weight_ih_l02"]);
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kOUTPUT, true, weightMap[lname + ".weight_ih_l03"]);
|
||||||
|
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kINPUT, false, weightMap[lname + ".weight_hh_l00"]);
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kFORGET, false, weightMap[lname + ".weight_hh_l01"]);
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kCELL, false, weightMap[lname + ".weight_hh_l02"]);
|
||||||
|
lstm->setWeightsForGate(0, RNNGateType::kOUTPUT, false, weightMap[lname + ".weight_hh_l03"]);
|
||||||
|
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kINPUT, true, weightMap[lname + ".bias_ih_l00"]);
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kFORGET, true, weightMap[lname + ".bias_ih_l01"]);
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kCELL, true, weightMap[lname + ".bias_ih_l02"]);
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kOUTPUT, true, weightMap[lname + ".bias_ih_l03"]);
|
||||||
|
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kINPUT, false, weightMap[lname + ".bias_hh_l00"]);
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kFORGET, false, weightMap[lname + ".bias_hh_l01"]);
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kCELL, false, weightMap[lname + ".bias_hh_l02"]);
|
||||||
|
lstm->setBiasForGate(0, RNNGateType::kOUTPUT, false, weightMap[lname + ".bias_hh_l03"]);
|
||||||
|
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kINPUT, true, weightMap[lname + ".weight_ih_l0_reverse0"]);
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kFORGET, true, weightMap[lname + ".weight_ih_l0_reverse1"]);
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kCELL, true, weightMap[lname + ".weight_ih_l0_reverse2"]);
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kOUTPUT, true, weightMap[lname + ".weight_ih_l0_reverse3"]);
|
||||||
|
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kINPUT, false, weightMap[lname + ".weight_hh_l0_reverse0"]);
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kFORGET, false, weightMap[lname + ".weight_hh_l0_reverse1"]);
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kCELL, false, weightMap[lname + ".weight_hh_l0_reverse2"]);
|
||||||
|
lstm->setWeightsForGate(1, RNNGateType::kOUTPUT, false, weightMap[lname + ".weight_hh_l0_reverse3"]);
|
||||||
|
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kINPUT, true, weightMap[lname + ".bias_ih_l0_reverse0"]);
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kFORGET, true, weightMap[lname + ".bias_ih_l0_reverse1"]);
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kCELL, true, weightMap[lname + ".bias_ih_l0_reverse2"]);
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kOUTPUT, true, weightMap[lname + ".bias_ih_l0_reverse3"]);
|
||||||
|
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kINPUT, false, weightMap[lname + ".bias_hh_l0_reverse0"]);
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kFORGET, false, weightMap[lname + ".bias_hh_l0_reverse1"]);
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kCELL, false, weightMap[lname + ".bias_hh_l0_reverse2"]);
|
||||||
|
lstm->setBiasForGate(1, RNNGateType::kOUTPUT, false, weightMap[lname + ".bias_hh_l0_reverse3"]);
|
||||||
|
return lstm;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creat the engine using only the API and not any parser.
|
||||||
|
ICudaEngine* createEngine(unsigned int maxBatchSize, IBuilder* builder, IBuilderConfig* config, DataType dt) {
|
||||||
|
INetworkDefinition* network = builder->createNetworkV2(0U);
|
||||||
|
|
||||||
|
// Create input tensor of shape {C, INPUT_H, INPUT_W} with name INPUT_BLOB_NAME
|
||||||
|
ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{1, INPUT_H, INPUT_W});
|
||||||
|
assert(data);
|
||||||
|
|
||||||
|
std::map<std::string, Weights> weightMap = loadWeights("../crnn.wts");
|
||||||
|
|
||||||
|
// cnn
|
||||||
|
auto x = convRelu(network, weightMap, *data, 0);
|
||||||
|
auto p = network->addPoolingNd(*x->getOutput(0), PoolingType::kMAX, DimsHW{2, 2});
|
||||||
|
p->setStrideNd(DimsHW{2, 2});
|
||||||
|
x = convRelu(network, weightMap, *p->getOutput(0), 1);
|
||||||
|
p = network->addPoolingNd(*x->getOutput(0), PoolingType::kMAX, DimsHW{2, 2});
|
||||||
|
p->setStrideNd(DimsHW{2, 2});
|
||||||
|
x = convRelu(network, weightMap, *p->getOutput(0), 2, true);
|
||||||
|
x = convRelu(network, weightMap, *x->getOutput(0), 3);
|
||||||
|
p = network->addPoolingNd(*x->getOutput(0), PoolingType::kMAX, DimsHW{2, 2});
|
||||||
|
p->setStrideNd(DimsHW{2, 1});
|
||||||
|
p->setPaddingNd(DimsHW{0, 1});
|
||||||
|
x = convRelu(network, weightMap, *p->getOutput(0), 4, true);
|
||||||
|
x = convRelu(network, weightMap, *x->getOutput(0), 5);
|
||||||
|
p = network->addPoolingNd(*x->getOutput(0), PoolingType::kMAX, DimsHW{2, 2});
|
||||||
|
p->setStrideNd(DimsHW{2, 1});
|
||||||
|
p->setPaddingNd(DimsHW{0, 1});
|
||||||
|
x = convRelu(network, weightMap, *p->getOutput(0), 6, true);
|
||||||
|
|
||||||
|
auto sfl = network->addShuffle(*x->getOutput(0));
|
||||||
|
sfl->setFirstTranspose(Permutation{1, 2, 0});
|
||||||
|
|
||||||
|
// rnn
|
||||||
|
auto lstm0 = addLSTM(network, weightMap, *sfl->getOutput(0), 256, "rnn.0.rnn");
|
||||||
|
auto sfl0 = network->addShuffle(*lstm0->getOutput(0));
|
||||||
|
sfl0->setReshapeDimensions(Dims4{26, 1, 1, 512});
|
||||||
|
auto fc0 = network->addFullyConnected(*sfl0->getOutput(0), 256, weightMap["rnn.0.embedding.weight"], weightMap["rnn.0.embedding.bias"]);
|
||||||
|
|
||||||
|
sfl = network->addShuffle(*fc0->getOutput(0));
|
||||||
|
sfl->setFirstTranspose(Permutation{2, 3, 0, 1});
|
||||||
|
sfl->setReshapeDimensions(Dims3{1, 26, 256});
|
||||||
|
|
||||||
|
auto lstm1 = addLSTM(network, weightMap, *sfl->getOutput(0), 256, "rnn.1.rnn");
|
||||||
|
auto sfl1 = network->addShuffle(*lstm1->getOutput(0));
|
||||||
|
sfl1->setReshapeDimensions(Dims4{26, 1, 1, 512});
|
||||||
|
auto fc1 = network->addFullyConnected(*sfl1->getOutput(0), 37, weightMap["rnn.1.embedding.weight"], weightMap["rnn.1.embedding.bias"]);
|
||||||
|
Dims dims = fc1->getOutput(0)->getDimensions();
|
||||||
|
std::cout << "fc1 shape " << dims.d[0] << " " << dims.d[1] << " " << dims.d[2] << std::endl;
|
||||||
|
|
||||||
|
fc1->getOutput(0)->setName(OUTPUT_BLOB_NAME);
|
||||||
|
network->markOutput(*fc1->getOutput(0));
|
||||||
|
|
||||||
|
// Build engine
|
||||||
|
builder->setMaxBatchSize(maxBatchSize);
|
||||||
|
config->setMaxWorkspaceSize(16 * (1 << 20)); // 16MB
|
||||||
|
#ifdef USE_FP16
|
||||||
|
config->setFlag(BuilderFlag::kFP16);
|
||||||
|
#endif
|
||||||
|
std::cout << "Building engine, please wait for a while..." << std::endl;
|
||||||
|
ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
|
||||||
|
std::cout << "Build engine successfully!" << 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);
|
||||||
|
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);
|
||||||
|
assert(engine != nullptr);
|
||||||
|
|
||||||
|
// Serialize the engine
|
||||||
|
(*modelStream) = engine->serialize();
|
||||||
|
|
||||||
|
// Close everything down
|
||||||
|
engine->destroy();
|
||||||
|
builder->destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
void doInference(IExecutionContext& context, cudaStream_t& stream, void **buffers, float* input, float* output, int batchSize) {
|
||||||
|
// DMA input batch data to device, infer on the batch asynchronously, and DMA output back to host
|
||||||
|
CHECK(cudaMemcpyAsync(buffers[0], input, batchSize * 1 * INPUT_H * INPUT_W * sizeof(float), cudaMemcpyHostToDevice, stream));
|
||||||
|
context.enqueue(batchSize, buffers, stream, nullptr);
|
||||||
|
CHECK(cudaMemcpyAsync(output, buffers[1], batchSize * OUTPUT_SIZE * sizeof(float), cudaMemcpyDeviceToHost, stream));
|
||||||
|
cudaStreamSynchronize(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
cudaSetDevice(DEVICE);
|
||||||
|
// create a model using the API directly and serialize it to a stream
|
||||||
|
char *trtModelStream{nullptr};
|
||||||
|
size_t size{0};
|
||||||
|
if (argc == 2 && std::string(argv[1]) == "-s") {
|
||||||
|
IHostMemory* modelStream{nullptr};
|
||||||
|
APIToModel(BATCH_SIZE, &modelStream);
|
||||||
|
assert(modelStream != nullptr);
|
||||||
|
std::ofstream p("crnn.engine", std::ios::binary);
|
||||||
|
if (!p) {
|
||||||
|
std::cerr << "could not open plan output file" << std::endl;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
p.write(reinterpret_cast<const char*>(modelStream->data()), modelStream->size());
|
||||||
|
modelStream->destroy();
|
||||||
|
return 0;
|
||||||
|
} else if (argc == 2 && std::string(argv[1]) == "-d") {
|
||||||
|
std::ifstream file("crnn.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 {
|
||||||
|
std::cerr << "arguments not right!" << std::endl;
|
||||||
|
std::cerr << "./crnn -s // serialize model to plan file" << std::endl;
|
||||||
|
std::cerr << "./crnn -d ../samples // deserialize plan file and run inference" << std::endl;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepare input data ---------------------------
|
||||||
|
static float data[BATCH_SIZE * 1 * INPUT_H * INPUT_W];
|
||||||
|
//for (int i = 0; i < 1 * INPUT_H * INPUT_W; i++)
|
||||||
|
// data[i] = 1.0;
|
||||||
|
static float prob[BATCH_SIZE * OUTPUT_SIZE];
|
||||||
|
IRuntime* runtime = createInferRuntime(gLogger);
|
||||||
|
assert(runtime != nullptr);
|
||||||
|
ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size);
|
||||||
|
assert(engine != nullptr);
|
||||||
|
IExecutionContext* context = engine->createExecutionContext();
|
||||||
|
assert(context != nullptr);
|
||||||
|
delete[] trtModelStream;
|
||||||
|
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);
|
||||||
|
assert(inputIndex == 0);
|
||||||
|
assert(outputIndex == 1);
|
||||||
|
// Create GPU buffers on device
|
||||||
|
CHECK(cudaMalloc(&buffers[inputIndex], BATCH_SIZE * 1 * INPUT_H * INPUT_W * sizeof(float)));
|
||||||
|
CHECK(cudaMalloc(&buffers[outputIndex], BATCH_SIZE * OUTPUT_SIZE * sizeof(float)));
|
||||||
|
// Create stream
|
||||||
|
cudaStream_t stream;
|
||||||
|
CHECK(cudaStreamCreate(&stream));
|
||||||
|
|
||||||
|
cv::Mat img = cv::imread("demo.png");
|
||||||
|
if (img.empty()) {
|
||||||
|
std::cerr << "demo.png not found !!!" << std::endl;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
cv::cvtColor(img, img, CV_BGR2GRAY);
|
||||||
|
cv::resize(img, img, cv::Size(INPUT_W, INPUT_H));
|
||||||
|
for (int i = 0; i < INPUT_H * INPUT_W; i++) {
|
||||||
|
data[i] = ((float)img.at<uchar>(i) / 255.0 - 0.5) * 2.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run inference
|
||||||
|
auto start = std::chrono::system_clock::now();
|
||||||
|
doInference(*context, stream, buffers, data, prob, BATCH_SIZE);
|
||||||
|
auto end = std::chrono::system_clock::now();
|
||||||
|
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
|
||||||
|
|
||||||
|
std::vector<int> preds;
|
||||||
|
for (int i = 0; i < 26; i++) {
|
||||||
|
int maxj = 0;
|
||||||
|
for (int j = 1; j < 37; j++) {
|
||||||
|
if (prob[37 * i + j] > prob[37 * i + maxj]) maxj = j;
|
||||||
|
}
|
||||||
|
preds.push_back(maxj);
|
||||||
|
}
|
||||||
|
std::cout << "raw: " << strDecode(preds, true) << std::endl;
|
||||||
|
std::cout << "sim: " << strDecode(preds, false) << std::endl;
|
||||||
|
|
||||||
|
// Release stream and buffers
|
||||||
|
cudaStreamDestroy(stream);
|
||||||
|
CHECK(cudaFree(buffers[inputIndex]));
|
||||||
|
CHECK(cudaFree(buffers[outputIndex]));
|
||||||
|
// 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 << std::endl;
|
||||||
|
//}
|
||||||
|
//std::cout << std::endl;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
35
crnn/genwts.py
Normal file
35
crnn/genwts.py
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import torch
|
||||||
|
from torch.autograd import Variable
|
||||||
|
import utils
|
||||||
|
import models.crnn as crnn
|
||||||
|
import struct
|
||||||
|
|
||||||
|
model_path = './data/crnn.pth'
|
||||||
|
|
||||||
|
model = crnn.CRNN(32, 1, 37, 256)
|
||||||
|
if torch.cuda.is_available():
|
||||||
|
model = model.cuda()
|
||||||
|
print('loading pretrained model from %s' % model_path)
|
||||||
|
model.load_state_dict(torch.load(model_path))
|
||||||
|
|
||||||
|
image = torch.ones(1, 1, 32, 100)
|
||||||
|
if torch.cuda.is_available():
|
||||||
|
image = image.cuda()
|
||||||
|
|
||||||
|
model.eval()
|
||||||
|
print(model)
|
||||||
|
print('image shape ', image.shape)
|
||||||
|
preds = model(image)
|
||||||
|
|
||||||
|
f = open("crnn.wts", 'w')
|
||||||
|
f.write("{}\n".format(len(model.state_dict().keys())))
|
||||||
|
for k,v in model.state_dict().items():
|
||||||
|
print('key: ', k)
|
||||||
|
print('value: ', v.shape)
|
||||||
|
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")
|
||||||
|
|
||||||
503
crnn/logging.h
Normal file
503
crnn/logging.h
Normal file
@ -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 <cassert>
|
||||||
|
#include <ctime>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <iostream>
|
||||||
|
#include <ostream>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
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
|
||||||
Loading…
Reference in New Issue
Block a user