16#include <NvInferPlugin.h>
17#include <NvInferRuntimeCommon.h>
18#include <NvInferVersion.h>
20#ifdef NV_TENSORRT_MAJOR
21#if NV_TENSORRT_MAJOR == 8
32#include <cuda_runtime_api.h>
34#include "absl/strings/str_cat.h"
47 void log(Severity severity,
const char *msg)
noexcept override {
49 case Severity::kINTERNAL_ERROR:
50 case Severity::kERROR:
53 case Severity::kWARNING:
57 case Severity::kVERBOSE:
72 nvinfer1::ILayer *layer,
TensorMap *tensor_map,
74 for (
int i = 0; i < layer_param.top_size(); ++i) {
75 std::string top_name = layer_param.
top(i);
76 TensorModifyMap::iterator it;
77 it = tensor_modify_map->find(top_name);
78 if (it != tensor_modify_map->end()) {
79 std::string modify_name = top_name +
"_" + layer_param.
name();
80 top_name = modify_name;
81 it->second = top_name;
83 tensor_modify_map->insert(
84 std::pair<std::string, std::string>(top_name, top_name));
86 tensor_map->insert(std::pair<std::string, nvinfer1::ITensor *>(
87 top_name, layer->getOutput(i)));
88 layer->getOutput(i)->setName(top_name.c_str());
93 nvinfer1::ITensor *
const *inputs,
95 nvinfer1::INetworkDefinition *net,
101 nvinfer1::IConvolutionLayer *convLayer = NULL;
103 inputs[0]->getDimensions().d[0];
106 nvinfer1::Weights bias_weight{nvinfer1::DataType::kFLOAT,
nullptr, 0};
107 convLayer = net->addConvolution(
108 *inputs[0],
static_cast<int>((conv.
num_output())),
109 nvinfer1::DimsHW{param.kernel_h, param.kernel_w}, wt, bias_weight);
110 if ((*weight_map)[layer_param.
name().c_str()].size() > 0) {
111 convLayer->setKernelWeights((*weight_map)[layer_param.
name().c_str()][0]);
113 if ((*weight_map)[layer_param.
name().c_str()].size() > 1) {
114 convLayer->setBiasWeights((*weight_map)[layer_param.
name().c_str()][1]);
117 std::vector<nvinfer1::Weights> lw;
119 lw[0] = convLayer->getKernelWeights();
120 lw[1] = convLayer->getBiasWeights();
121 (*weight_map)[layer_param.
name().c_str()] = lw;
125 convLayer->setNbGroups(conv.
group());
126 convLayer->setName(layer_param.
name().c_str());
128 ConstructMap(layer_param, convLayer, tensor_map, tensor_modify_map);
131 auto tmp_out_dims = convLayer->getOutput(0)->getDimensions();
132 std::string dim_string =
"input: ";
133 for (
int i = 0; i < 3; ++i) {
134 absl::StrAppend(&dim_string,
" ",
135 convLayer->getInput(0)->getDimensions().d[i]);
137 absl::StrAppend(&dim_string,
" | output: ");
138 for (
int i = 0; i < 3; ++i) {
139 absl::StrAppend(&dim_string,
" ", tmp_out_dims.d[i]);
141 AINFO << layer_param.
name() << dim_string;
146 nvinfer1::ITensor *
const *inputs,
148 nvinfer1::INetworkDefinition *net,
154 nvinfer1::IDeconvolutionLayer *deconvLayer =
nullptr;
155 if ((*weight_map)[layer_param.
name().c_str()].size() == 2) {
157 net->addDeconvolution(*inputs[0], conv.
num_output(),
158 nvinfer1::DimsHW{param.kernel_h, param.kernel_w},
159 (*weight_map)[layer_param.
name().c_str()][0],
160 (*weight_map)[layer_param.
name().c_str()][1]);
162 nvinfer1::Weights bias_weight{nvinfer1::DataType::kFLOAT,
nullptr, 0};
163 deconvLayer = net->addDeconvolution(
165 nvinfer1::DimsHW{param.kernel_h, param.kernel_w},
166 (*weight_map)[layer_param.
name().c_str()][0], bias_weight);
170 deconvLayer->setPaddingMode(nvinfer1::PaddingMode::kCAFFE_ROUND_DOWN);
171 deconvLayer->setNbGroups(conv.
group());
173 deconvLayer->setName(layer_param.
name().c_str());
174 ConstructMap(layer_param, deconvLayer, tensor_map, tensor_modify_map);
177 std::string dim_string =
"input: ";
178 for (
int i = 0; i < 3; ++i) {
179 absl::StrAppend(&dim_string,
" ", inputs[0]->getDimensions().d[i]);
181 absl::StrAppend(&dim_string,
" | output: ");
182 AINFO << layer_param.
name() << dim_string;
186 nvinfer1::ITensor *
const *inputs,
int nbInputs,
187 nvinfer1::INetworkDefinition *net,
190 if (layer_param.
type() ==
"ReLU" &&
192 std::shared_ptr<ReLUPlugin> relu_plugin;
194 new ReLUPlugin(layer_param.
relu_param(), inputs[0]->getDimensions()));
195#ifdef NV_TENSORRT_MAJOR
196#if NV_TENSORRT_MAJOR != 8
197 nvinfer1::IPluginLayer *ReLU_Layer =
198 net->addPlugin(inputs, nbInputs, *relu_plugin);
200 nvinfer1::IPluginV2Layer *ReLU_Layer =
201 net->addPluginV2(inputs, nbInputs, *relu_plugin);
204 relu_plugins_.push_back(relu_plugin);
205 ReLU_Layer->setName(layer_param.
name().c_str());
206 ConstructMap(layer_param, ReLU_Layer, tensor_map, tensor_modify_map);
208 nvinfer1::ActivationType type = nvinfer1::ActivationType::kSIGMOID;
213 nvinfer1::IActivationLayer *reluLayer =
214 net->addActivation(*inputs[0], type);
215 reluLayer->setName(layer_param.
name().c_str());
217 ConstructMap(layer_param, reluLayer, tensor_map, tensor_modify_map);
222 nvinfer1::ITensor *
const *inputs,
int nbInputs,
223 nvinfer1::INetworkDefinition *net,
227 nvinfer1::IConcatenationLayer *concatLayer =
228 net->addConcatenation(inputs, nbInputs);
231 concatLayer->setAxis(concat.
axis() - 1);
232 concatLayer->setName(layer_param.
name().c_str());
233 CHECK_EQ(nbInputs, layer_param.bottom_size());
236 std::string dim_string =
"";
237 for (
int i = 0; i < nbInputs; ++i) {
238 auto dim_tmp = inputs[i]->getDimensions();
239 for (
int i = 0; i < 3; ++i) {
240 absl::StrAppend(&dim_string,
" ", dim_tmp.d[i]);
243 << (*tensor_modify_map)[layer_param.
bottom(i)] <<
" " << dim_string;
246 ConstructMap(layer_param, concatLayer, tensor_map, tensor_modify_map);
250 nvinfer1::ITensor *
const *inputs,
251 nvinfer1::INetworkDefinition *net,
255 nvinfer1::PoolingType pool_type =
256 (pool.
pool() == PoolingParameter_PoolMethod_MAX)
257 ? nvinfer1::PoolingType::kMAX
258 : nvinfer1::PoolingType::kAVERAGE;
259 nvinfer1::PaddingMode padding_mode = nvinfer1::PaddingMode::kCAFFE_ROUND_UP;
260 if (pool.has_round_mode()) {
261 switch (
static_cast<int>(pool.
round_mode())) {
263 padding_mode = nvinfer1::PaddingMode::kCAFFE_ROUND_UP;
266 padding_mode = nvinfer1::PaddingMode::kCAFFE_ROUND_DOWN;
269 padding_mode = nvinfer1::PaddingMode::kCAFFE_ROUND_UP;
273 nvinfer1::IPoolingLayer *poolLayer = net->addPooling(
274 *inputs[0], pool_type,
276 poolLayer->setStride(nvinfer1::DimsHW{
static_cast<int>(pool.
stride_h()),
277 static_cast<int>(pool.
stride_w())});
278 poolLayer->setPadding(nvinfer1::DimsHW{
static_cast<int>(pool.
pad_h()),
279 static_cast<int>(pool.
pad_w())});
280 poolLayer->setPaddingMode(padding_mode);
282 poolLayer->setAverageCountExcludesPadding(
false);
283 poolLayer->setName(layer_param.
name().c_str());
284 ConstructMap(layer_param, poolLayer, tensor_map, tensor_modify_map);
288 nvinfer1::ITensor *
const *inputs,
int nbInputs,
289 nvinfer1::INetworkDefinition *net,
292#ifdef NV_TENSORRT_MAJOR
293#if NV_TENSORRT_MAJOR != 8
295 std::shared_ptr<SLICEPlugin> slice_plugin;
297 new SLICEPlugin(layer_param.
slice_param(), inputs[0]->getDimensions()));
299 nvinfer1::IPluginLayer *sliceLayer =
300 net->addPlugin(inputs, nbInputs, *slice_plugin);
302 slice_plugins_.push_back(slice_plugin);
303 sliceLayer->setName(layer_param.
name().c_str());
304 ConstructMap(layer_param, sliceLayer, tensor_map, tensor_modify_map);
306 const auto mPluginRegistry = getPluginRegistry();
308 mPluginRegistry->getPluginCreator(
"slice_plugin",
"1",
"camera");
311 int axis = slice_param.
axis();
312 int slice_point_num = slice_param.slice_point_size();
313 std::vector<int> slice_point(slice_point_num);
315 for (
int i = 0; i < slice_point_num; i++) {
316 slice_point[i] = slice_param.slice_point(i);
318 nvinfer1::Dims in_dims = inputs[0]->getDimensions();
319 std::vector<nvinfer1::PluginField>
f;
320 f.emplace_back(nvinfer1::PluginField(
"axis", &axis,
321 nvinfer1::PluginFieldType::kINT32, 1));
322 f.emplace_back(nvinfer1::PluginField(
"slice_point", &slice_point[0],
323 nvinfer1::PluginFieldType::kINT32,
325 f.emplace_back(nvinfer1::PluginField(
"in_dims", &in_dims,
326 nvinfer1::PluginFieldType::kDIMS, 1));
327 nvinfer1::PluginFieldCollection fc;
328 fc.nbFields =
f.size();
329 fc.fields =
f.data();
331 nvinfer1::IPluginV2 *slice_plugin = creator->createPlugin(
"slice_layer", &fc);
333 nvinfer1::IPluginV2Layer *sliceLayer =
334 net->addPluginV2(inputs, nbInputs, *slice_plugin);
335 sliceLayer->setName(layer_param.
name().c_str());
337 ConstructMap(layer_param, sliceLayer, tensor_map, tensor_modify_map);
343 nvinfer1::ITensor *
const *inputs,
345 nvinfer1::INetworkDefinition *net,
349 nvinfer1::Weights bias{nvinfer1::DataType::kFLOAT,
nullptr, 0};
350 if ((*weight_map)[layer_param.
name().c_str()].size() == 2) {
351 bias = (*weight_map)[layer_param.
name().c_str()][1];
353 nvinfer1::IFullyConnectedLayer *fcLayer = net->addFullyConnected(
354 *inputs[0], fc.
num_output(), (*weight_map)[layer_param.
name().c_str()][0],
356 fcLayer->setName(layer_param.
name().c_str());
357 ConstructMap(layer_param, fcLayer, tensor_map, tensor_modify_map);
361 nvinfer1::ITensor *
const *inputs,
363 nvinfer1::INetworkDefinition *net,
366 std::vector<nvinfer1::Weights> lw(
367 3, nvinfer1::Weights{nvinfer1::DataType::kFLOAT,
nullptr, 0});
368 if (layer_param.
type() ==
"Power") {
370 nvinfer1::Dims input_dim = inputs[0]->getDimensions();
371 int size = input_dim.d[0];
376 ACHECK(weight_map->find(layer_param.
name().c_str()) != weight_map->end());
377 for (
size_t i = 0; i < (*weight_map)[layer_param.
name().c_str()].size();
379 lw[i] = (*weight_map)[layer_param.
name().c_str()][i];
382 (*weight_map)[layer_param.
name().c_str()] = lw;
384 nvinfer1::IScaleLayer *scaleLayer = net->addScale(
385 *inputs[0], nvinfer1::ScaleMode::kCHANNEL, lw[1], lw[0], lw[2]);
386 scaleLayer->setName(layer_param.
name().c_str());
387 ConstructMap(layer_param, scaleLayer, tensor_map, tensor_modify_map);
391 nvinfer1::ITensor *
const *inputs,
393 nvinfer1::INetworkDefinition *net,
397 nvinfer1::Weights power{nvinfer1::DataType::kFLOAT,
nullptr, 0};
399 nvinfer1::IScaleLayer *scaleLayer =
400 net->addScale(*inputs[0], nvinfer1::ScaleMode::kCHANNEL,
401 (*weight_map)[layer_param.
name().c_str()][0],
402 (*weight_map)[layer_param.
name().c_str()][1], power);
403 scaleLayer->setName(layer_param.
name().c_str());
405 ConstructMap(layer_param, scaleLayer, tensor_map, tensor_modify_map);
408 nvinfer1::ITensor *
const *inputs,
int nbInputs,
409 nvinfer1::INetworkDefinition *net,
412 if (layer_param.has_softmax_param()) {
413#ifdef NV_TENSORRT_MAJOR
414#if NV_TENSORRT_MAJOR != 8
415 std::shared_ptr<SoftmaxPlugin> softmax_plugin;
416 softmax_plugin.reset(
new SoftmaxPlugin(layer_param.
softmax_param(),
417 inputs[0]->getDimensions()));
418 softmax_plugins_.push_back(softmax_plugin);
420 nvinfer1::IPluginLayer *softmaxLayer =
421 net->addPlugin(inputs, nbInputs, *softmax_plugin);
423 softmaxLayer->setName(layer_param.
name().c_str());
425 ConstructMap(layer_param, softmaxLayer, tensor_map, tensor_modify_map);
427 const auto mPluginRegistry = getPluginRegistry();
429 mPluginRegistry->getPluginCreator(
"softmax_plugin",
"1",
"camera");
432 int axis = softmax_param.
axis();
433 nvinfer1::Dims in_dims = inputs[0]->getDimensions();
434 std::vector<nvinfer1::PluginField>
f;
435 f.emplace_back(nvinfer1::PluginField(
"axis", &axis,
436 nvinfer1::PluginFieldType::kINT32, 1));
437 f.emplace_back(nvinfer1::PluginField(
"in_dims", &in_dims,
438 nvinfer1::PluginFieldType::kDIMS, 1));
440 nvinfer1::PluginFieldCollection fc;
441 fc.nbFields =
f.size();
442 fc.fields =
f.data();
443 nvinfer1::IPluginV2 *softmax_plugin =
444 creator->createPlugin(
"softmax_layer", &fc);
446 nvinfer1::IPluginV2Layer *softmaxLayer =
447 net->addPluginV2(inputs, nbInputs, *softmax_plugin);
448 softmaxLayer->setName(layer_param.
name().c_str());
449 ConstructMap(layer_param, softmaxLayer, tensor_map, tensor_modify_map);
453 nvinfer1::ISoftMaxLayer *softmaxLayer = net->addSoftMax(*inputs[0]);
454 softmaxLayer->setName(layer_param.
name().c_str());
455 ConstructMap(layer_param, softmaxLayer, tensor_map, tensor_modify_map);
460 nvinfer1::ITensor *
const *inputs,
461 nvinfer1::INetworkDefinition *net,
465 nvinfer1::ElementWiseOperation op = nvinfer1::ElementWiseOperation::kSUM;
469 nvinfer1::IElementWiseLayer *eltwiseLayer =
470 net->addElementWise(*inputs[0], *inputs[1], op);
472 eltwiseLayer->setName(layer_param.
name().c_str());
473 ConstructMap(layer_param, eltwiseLayer, tensor_map, tensor_modify_map);
477 nvinfer1::ITensor *
const *inputs,
int nbInputs,
478 nvinfer1::INetworkDefinition *net,
481 std::shared_ptr<ArgMax1Plugin> argmax_plugin;
482 argmax_plugin.reset(
new ArgMax1Plugin(layer_param.
argmax_param(),
483 inputs[0]->getDimensions()));
484 argmax_plugins_.push_back(argmax_plugin);
485#ifdef NV_TENSORRT_MAJOR
486#if NV_TENSORRT_MAJOR != 8
487 nvinfer1::IPluginLayer *argmaxLayer =
488 net->addPlugin(inputs, nbInputs, *argmax_plugin);
490 nvinfer1::IPluginV2Layer *argmaxLayer =
491 net->addPluginV2(inputs, nbInputs, *argmax_plugin);
495 argmaxLayer->setName(layer_param.
name().c_str());
496 ConstructMap(layer_param, argmaxLayer, tensor_map, tensor_modify_map);
500 nvinfer1::ITensor *
const *inputs,
int nbInputs,
501 nvinfer1::INetworkDefinition *net,
504 CHECK_LE(layer_param.
permute_param().order_size(), nvinfer1::Dims::MAX_DIMS);
505 nvinfer1::IShuffleLayer *permuteLayer = net->addShuffle(*inputs[0]);
506 nvinfer1::Permutation permutation;
511 for (
int i = 1; i < layer_param.
permute_param().order_size(); ++i) {
513 permutation.order[i - 1] = order - 1;
515 permuteLayer->setFirstTranspose(permutation);
517 permuteLayer->setName(layer_param.
name().c_str());
518 ConstructMap(layer_param, permuteLayer, tensor_map, tensor_modify_map);
522 nvinfer1::ITensor *
const *inputs,
523 nvinfer1::INetworkDefinition *net,
530 nvinfer1::IShuffleLayer *reshapeLayer = net->addShuffle(*inputs[0]);
531 reshapeLayer->setReshapeDimensions(dims);
532 reshapeLayer->setName(layer_param.
name().c_str());
533 ConstructMap(layer_param, reshapeLayer, tensor_map, tensor_modify_map);
537 nvinfer1::ITensor *
const *inputs,
538 nvinfer1::INetworkDefinition *net,
545 nvinfer1::IPaddingLayer *padding_layer =
546 net->addPadding(*inputs[0], pre_dims, post_dims);
547 padding_layer->setName(layer_param.
name().c_str());
548 ConstructMap(layer_param, padding_layer, tensor_map, tensor_modify_map);
552 nvinfer1::ITensor *
const *inputs,
554 nvinfer1::INetworkDefinition *net,
557 std::shared_ptr<DFMBPSROIAlignPlugin> dfmb_psroi_align_plugin;
558 nvinfer1::Dims input_dims[3];
559 for (
int i = 0; i < nbInputs && i < 3; ++i) {
560 input_dims[i] = inputs[i]->getDimensions();
564 dfmb_psroi_align_plugins_.push_back(dfmb_psroi_align_plugin);
565#ifdef NV_TENSORRT_MAJOR
566#if NV_TENSORRT_MAJOR != 8
567 nvinfer1::IPluginLayer *dfmb_psroi_align_layer =
568 net->addPlugin(inputs, nbInputs, *dfmb_psroi_align_plugin);
570 nvinfer1::IPluginV2Layer *dfmb_psroi_align_layer =
571 net->addPluginV2(inputs, nbInputs, *dfmb_psroi_align_plugin);
574 dfmb_psroi_align_layer->setName(layer_param.
name().c_str());
576 ConstructMap(layer_param, dfmb_psroi_align_layer, tensor_map,
581 nvinfer1::ITensor *
const *inputs,
int nbInputs,
582 nvinfer1::INetworkDefinition *net,
585 std::shared_ptr<RCNNProposalPlugin> rcnn_proposal_plugin;
586 nvinfer1::Dims input_dims[4];
587 for (
int i = 0; i < nbInputs && i < 4; ++i) {
588 input_dims[i] = inputs[i]->getDimensions();
593 rcnn_proposal_plugins_.push_back(rcnn_proposal_plugin);
594#ifdef NV_TENSORRT_MAJOR
595#if NV_TENSORRT_MAJOR != 8
596 nvinfer1::IPluginLayer *rcnn_proposal_layer =
597 net->addPlugin(inputs, nbInputs, *rcnn_proposal_plugin);
599 nvinfer1::IPluginV2Layer *rcnn_proposal_layer =
600 net->addPluginV2(inputs, nbInputs, *rcnn_proposal_plugin);
603 rcnn_proposal_layer->setName(layer_param.
name().c_str());
605 ConstructMap(layer_param, rcnn_proposal_layer, tensor_map, tensor_modify_map);
609 nvinfer1::ITensor *
const *inputs,
611 nvinfer1::INetworkDefinition *net,
614 std::shared_ptr<RPNProposalSSDPlugin> rpn_proposal_ssd_plugin;
615 nvinfer1::Dims input_dims[3];
616 for (
int i = 0; i < nbInputs && i < 3; ++i) {
617 input_dims[i] = inputs[i]->getDimensions();
622 rpn_proposal_ssd_plugins_.push_back(rpn_proposal_ssd_plugin);
623#ifdef NV_TENSORRT_MAJOR
624#if NV_TENSORRT_MAJOR != 8
625 nvinfer1::IPluginLayer *rpn_proposal_ssd_layer =
626 net->addPlugin(inputs, nbInputs, *rpn_proposal_ssd_plugin);
628 nvinfer1::IPluginV2Layer *rpn_proposal_ssd_layer =
629 net->addPluginV2(inputs, nbInputs, *rpn_proposal_ssd_plugin);
632 rpn_proposal_ssd_layer->setName(layer_param.
name().c_str());
634 ConstructMap(layer_param, rpn_proposal_ssd_layer, tensor_map,
639 nvinfer1::ITensor *
const *inputs,
int nbInputs,
640 WeightMap *weight_map, nvinfer1::INetworkDefinition *net,
643 if (layer_param.
type() ==
"Convolution") {
644 addConvLayer(layer_param, inputs, weight_map, net, tensor_map,
646 }
else if (layer_param.
type() ==
"Deconvolution") {
649 }
else if (layer_param.
type() ==
"Sigmoid" || layer_param.
type() ==
"TanH" ||
650 layer_param.
type() ==
"ReLU") {
653 }
else if (layer_param.
type() ==
"Concat") {
656 }
else if (layer_param.
type() ==
"Slice") {
657 addSliceLayer(layer_param, inputs, nbInputs, net, tensor_map,
659 }
else if (layer_param.
type() ==
"Reshape") {
660 addReshapeLayer(layer_param, inputs, net, tensor_map, tensor_modify_map);
661 }
else if (layer_param.
type() ==
"Padding") {
662 addPaddingLayer(layer_param, inputs, net, tensor_map, tensor_modify_map);
663 }
else if (layer_param.
type() ==
"Pooling") {
664 addPoolingLayer(layer_param, inputs, net, tensor_map, tensor_modify_map);
665 }
else if (layer_param.
type() ==
"Permute") {
668 }
else if (layer_param.
type() ==
"InnerProduct") {
671 }
else if (layer_param.
type() ==
"BatchNorm") {
674 }
else if (layer_param.
type() ==
"Scale") {
675 addScaleLayer(layer_param, inputs, weight_map, net, tensor_map,
677 }
else if (layer_param.
type() ==
"Softmax") {
680 }
else if (layer_param.
type() ==
"Eltwise") {
681 addEltwiseLayer(layer_param, inputs, net, tensor_map, tensor_modify_map);
682 }
else if (layer_param.
type() ==
"ArgMax") {
685 }
else if (layer_param.
type() ==
"Dropout") {
686 AINFO <<
"skip dropout";
687 }
else if (layer_param.
type() ==
"Power") {
688 addScaleLayer(layer_param, inputs, weight_map, net, tensor_map,
690 }
else if (layer_param.
type() ==
"DFMBPSROIAlign") {
693 }
else if (layer_param.
type() ==
"RCNNProposal") {
696 }
else if (layer_param.
type() ==
"RPNProposalSSD") {
700 AWARN <<
"unknown layer type:" << layer_param.
type();
706 AFATAL <<
"open file " << model_file <<
" failed";
709 for (
int i = 0; i < net.layer_size(); ++i) {
710 std::vector<nvinfer1::Weights> lw;
711 for (
int j = 0; j < net.
layer(i).blobs_size(); ++j) {
714 CHECK_EQ(blob->double_data_size(), 0);
715 CHECK_EQ(blob->double_diff_size(), 0);
716 CHECK_EQ(blob->diff_size(), 0);
717 CHECK_NE(blob->data_size(), 0);
718 if (net.
layer(i).
type() ==
"BatchNorm") {
719 mergeBN(j, net.mutable_layer(i));
724 (*weight_map)[net.
layer(i).
name().c_str()] = lw;
729 auto blob = (layer_param->mutable_blobs(index));
730 CHECK_EQ(blob->double_data_size(), 0);
731 CHECK_EQ(blob->double_diff_size(), 0);
732 CHECK_EQ(blob->diff_size(), 0);
733 CHECK_NE(blob->data_size(), 0);
734 int size = blob->data_size();
736 auto scale = (layer_param->
blobs(2));
737 const float scale_factor = scale.data(0) == 0 ? 0 : 1 / scale.data(0);
740 const BlobProto *var = (layer_param->mutable_blobs(index + 1));
741 for (
int k = 0; k < size; ++k) {
742 auto data = blob->
data(k);
744 k,
static_cast<float>(-data * scale_factor /
745 sqrt(var->
data(k) * scale_factor + epsilon)));
747 }
else if (index == 1) {
748 for (
int k = 0; k < size; ++k) {
749 blob->set_data(k, 1.0f /
static_cast<float>(sqrt(
750 blob->data(k) * scale_factor + epsilon)));
755 nvinfer1::Weights wt{nvinfer1::DataType::kFLOAT,
nullptr, 0};
756 std::shared_ptr<float> val;
757 val.reset(
new float[size]);
758 weights_mem_.push_back(val);
759 for (
int k = 0; k < size; ++k) {
760 val.get()[k] = data[k];
762 wt.values = val.get();
767 nvinfer1::Weights wt{nvinfer1::DataType::kFLOAT,
nullptr, 0};
768 std::shared_ptr<float> val;
769 val.reset(
new float[size]);
770 weights_mem_.push_back(val);
771 for (
int k = 0; k < size; ++k) {
774 wt.values = val.get();
779RTNet::RTNet(
const std::string &net_file,
const std::string &model_file,
780 const std::vector<std::string> &outputs,
781 const std::vector<std::string> &inputs)
782 : output_names_(outputs), input_names_(inputs) {
787RTNet::RTNet(
const std::string &net_file,
const std::string &model_file,
788 const std::vector<std::string> &outputs,
789 const std::vector<std::string> &inputs,
791 : output_names_(outputs), input_names_(inputs) {
795 calibrator_ = calibrator;
796 is_own_calibrator_ =
false;
798RTNet::RTNet(
const std::string &net_file,
const std::string &model_file,
799 const std::vector<std::string> &outputs,
800 const std::vector<std::string> &inputs,
801 const std::string &model_root)
802 : output_names_(outputs), input_names_(inputs), is_own_calibrator_(true) {
806 model_root_ = model_root;
814 auto engine = &(context_->getEngine());
815 if (tensor_modify_map_.find(name) == tensor_modify_map_.end()) {
816 AINFO <<
"can't get the shape of " << name;
819 int bindingIndex = engine->getBindingIndex(tensor_modify_map_[name].c_str());
820 if (bindingIndex >
static_cast<int>(buffers_.size())) {
824 engine->getBindingDimensions(bindingIndex));
827 (*res)[1] = dims.
c();
828 (*res)[2] = dims.
h();
829 (*res)[3] = dims.
w();
833 auto engine = &(context_->getEngine());
835 for (
auto name : *names) {
837 engine->getBindingIndex(tensor_modify_map_[name].c_str());
838 CHECK_LT(
static_cast<size_t>(bindingIndex), buffers_.size());
839 CHECK_GE(bindingIndex, 0);
842 engine->getBindingDimensions(bindingIndex));
844 cudaMalloc(&buffers_[bindingIndex], count *
sizeof(
float));
846 std::vector<int>
shape;
851 blob->set_gpu_data(
reinterpret_cast<float *
>(buffers_[bindingIndex]));
853 blobs_.insert(std::make_pair(name, blob));
857bool LoadCache(
const std::string &path) {
860 if (stat(path.c_str(), &buffer) != 0) {
861 AERROR <<
"[INFO] cannot find model cache : " << path
862 <<
", it will take minutes to generate...";
868bool RTNet::Init(
const std::map<std::string, std::vector<int>> &shapes) {
870 AINFO <<
"must use gpu mode";
873 BASE_GPU_CHECK(cudaSetDevice(
gpu_id_));
875 cudaStreamCreate(&stream_);
877 builder_ = nvinfer1::createInferBuilder(
rt_gLogger);
879 workspaceSize_ = 1 << 30;
881 cudaGetDeviceProperties(&prop,
gpu_id_);
882 bool int8_mode =
checkInt8(prop.name, calibrator_);
884#ifdef NV_TENSORRT_MAJOR
885#if NV_TENSORRT_MAJOR != 8
886 network_ = builder_->createNetwork();
890 builder_->setMaxWorkspaceSize(workspaceSize_);
892 builder_->setInt8Mode(int8_mode);
893 builder_->setInt8Calibrator(calibrator_);
895 builder_->setDebugSync(
true);
897 nvinfer1::ICudaEngine *engine = builder_->buildCudaEngine(*network_);
899 network_ = builder_->createNetworkV2(0U);
901 builder_config_ = builder_->createBuilderConfig();
903 builder_config_->setMaxWorkspaceSize(workspaceSize_);
906 builder_config_->setFlag(nvinfer1::BuilderFlag::kINT8);
908 builder_config_->setFlag(nvinfer1::BuilderFlag::kDEBUG);
910 builder_config_->setInt8Calibrator(calibrator_);
913 nvinfer1::ICudaEngine *engine =
nullptr;
914 auto trt_cache_path = model_root_ +
"/TRTengine.cache";
915 if (!LoadCache(trt_cache_path)) {
916 engine = builder_->buildEngineWithConfig(*network_, *builder_config_);
918 if (engine->serialize()) {
919 nvinfer1::IHostMemory *serialized_model(engine->serialize());
920 std::ofstream
f(trt_cache_path, std::ios::binary);
922 f.write(
reinterpret_cast<char *
>(serialized_model->data()),
923 serialized_model->size());
924 serialized_model->destroy();
925 AERROR <<
"Saving serialized model file to " << trt_cache_path;
928 AINFO <<
"Loading TensorRT engine from serialized model file...";
929 std::ifstream planFile(trt_cache_path);
931 if (!planFile.is_open()) {
932 AERROR <<
"Could not open serialized model";
937 AINFO <<
"success open serialized model";
938 std::stringstream planBuffer;
939 planBuffer << planFile.rdbuf();
940 std::string plan = planBuffer.str();
941 nvinfer1::IRuntime *runtime = nvinfer1::createInferRuntime(
rt_gLogger);
943 engine = runtime->deserializeCudaEngine(
944 static_cast<const void *
>(plan.data()), plan.size(),
nullptr);
949 context_ = engine->createExecutionContext();
950 buffers_.resize(input_names_.size() + output_names_.size());
953 AINFO <<
"engine init success";
957 nvinfer1::IInt8Calibrator *calibrator) {
958 if (calibrator ==
nullptr) {
959 AINFO <<
"Device Works on FP32 Mode.";
963 if (ref == gpu_name) {
964 AINFO <<
"Device Works on Int8 Mode.";
968 AWARN <<
"Device Not Supports Int8 Mode. Use FP32 Mode.";
969 calibrator_ =
nullptr;
973 const std::map<std::string, std::vector<int>> &shapes,
975 CHECK_GT(net_param_->layer_size(), 0);
976 input_names_.clear();
977 for (
auto dims_pair : tensor_dims_map) {
978 if (shapes.find(dims_pair.first) != shapes.end()) {
979 auto shape = shapes.at(dims_pair.first);
980 if (
static_cast<int>(
shape.size()) == dims_pair.second.nbDims + 1) {
982 for (
int i = 0; i < dims_pair.second.nbDims; ++i) {
983 dims_pair.second.d[i] =
shape[i + 1];
987 auto data = network_->addInput(
988 dims_pair.first.c_str(), nvinfer1::DataType::kFLOAT, dims_pair.second);
990 data->setName(dims_pair.first.c_str());
991 tensor_map->insert(std::make_pair(dims_pair.first, data));
992 input_names_.push_back(dims_pair.first);
998 const std::map<std::string, std::vector<int>> &shapes) {
999 CHECK_GT(net_param_->layer_size(), 0);
1000 std::vector<LayerParameter> order;
1003 ParseNetParam(*net_param_, &tensor_dims_map, &tensor_modify_map_, &order);
1004 addInput(tensor_dims_map, shapes, &tensor_map);
1005 for (
auto layer_param : order) {
1006 std::vector<nvinfer1::ITensor *> inputs;
1007 for (
int j = 0; j < layer_param.bottom_size(); ++j) {
1008 CHECK_NOTNULL(tensor_map[tensor_modify_map_[layer_param.bottom(j)]]);
1009 inputs.push_back(tensor_map[tensor_modify_map_[layer_param.bottom(j)]]);
1011 addLayer(layer_param, inputs.data(), layer_param.bottom_size(),
1012 &weight_map_, network_, &tensor_map, &tensor_modify_map_);
1015 CHECK_NE(output_names_.size(),
static_cast<size_t>(0));
1016 std::sort(output_names_.begin(), output_names_.end());
1017 auto last = std::unique(output_names_.begin(), output_names_.end());
1018 output_names_.erase(last, output_names_.end());
1019 for (
auto iter = output_names_.begin(); iter != output_names_.end();) {
1020 if (tensor_map.find(tensor_modify_map_[*iter]) != tensor_map.end()) {
1021 network_->markOutput(*tensor_map[tensor_modify_map_[*iter]]);
1024 AINFO <<
"Erase output: " << *iter;
1025 iter = output_names_.erase(iter);
1031 if (is_own_calibrator_ && calibrator_ !=
nullptr) {
1035 BASE_GPU_CHECK(cudaStreamDestroy(stream_));
1036 network_->destroy();
1037#ifdef NV_TENSORRT_MAJOR
1038#if NV_TENSORRT_MAJOR != 8
1039 builder_config_->destroy();
1042 context_->destroy();
1043 for (
auto buf : buffers_) {
1050 BASE_GPU_CHECK(cudaSetDevice(
gpu_id_));
1051 BASE_GPU_CHECK(cudaStreamSynchronize(stream_));
1052 for (
auto name : input_names_) {
1054 if (blob !=
nullptr) {
1064 for (
auto name : output_names_) {
1066 if (blob !=
nullptr) {
1071 BASE_GPU_CHECK(cudaStreamSynchronize(stream_));
1073 for (
auto name : output_names_) {
1075 if (blob !=
nullptr) {
1076 blob->mutable_gpu_data();
1081 auto iter = blobs_.find(name);
1082 if (iter == blobs_.end()) {
1085 return iter->second;
A wrapper around SyncedMemory holders serving as the basic computational unit for images,...
void addScaleLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, WeightMap *weight_map, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addRCNNProposalLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addSoftmaxLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addPermuteLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addConcatLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addDFMBPSROIAlignLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addConvLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, WeightMap *weight_map, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void parse_with_api(const std::map< std::string, std::vector< int > > &shapes)
bool checkInt8(const std::string &gpu_name, nvinfer1::IInt8Calibrator *calibrator)
void addRPNProposalSSDLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, WeightMap *weight_map, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
bool loadWeights(const std::string &model_file, WeightMap *weight_map)
void addArgmaxLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void init_blob(std::vector< std::string > *names)
void addInnerproductLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, WeightMap *weight_map, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
RTNet(const std::string &net_file, const std::string &model_file, const std::vector< std::string > &outputs, const std::vector< std::string > &inputs)
void addActiveLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addSliceLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, int nbInputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
bool addInput(const TensorDimsMap &tensor_dims_map, const std::map< std::string, std::vector< int > > &shapes, TensorMap *tensor_map)
void addBatchnormLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, WeightMap *weight_map, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
base::BlobPtr< float > get_blob(const std::string &name) override
nvinfer1::Weights loadLayerWeights(const float *data, int size)
bool shape(const std::string &name, std::vector< int > *res)
void addEltwiseLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
bool Init(const std::map< std::string, std::vector< int > > &shapes) override
void mergeBN(int index, LayerParameter *layer_param)
void addPaddingLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addDeconvLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, WeightMap *weight_map, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addPoolingLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void addReshapeLayer(const LayerParameter &layer_param, nvinfer1::ITensor *const *inputs, nvinfer1::INetworkDefinition *net, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
void ConstructMap(const LayerParameter &layer_param, nvinfer1::ILayer *layer, TensorMap *tensor_map, TensorModifyMap *tensor_modify_map)
std::shared_ptr< Blob< Dtype > > BlobPtr
bool ParserConvParam(const ConvolutionParameter &conv, ConvParam *param)
std::map< std::string, Tensor > TensorMap
const std::map< EltwiseParameter::EltwiseOp, std::string > eltwise_map
void ParseNetParam(const NetParameter &net_param, TensorDimsMap *tensor_dims_map, std::map< std::string, std::string > *tensor_modify_map, std::vector< LayerParameter > *order)
std::map< std::string, std::string > TensorModifyMap
const std::map< std::string, std::string > active_map
const std::vector< std::string > _gpu_checklist
bool loadNetParams(const std::string ¶m_file, NetParameter *param)
std::map< std::string, TensorDims > TensorDimsMap
bool ReadProtoFromBinaryFile(const std::string &filename, google::protobuf::Message *proto)
bool modify_pool_param(PoolingParameter *pool_param)
std::map< std::string, std::vector< Weights > > WeightMap
optional uint32 num_output
optional FillerParameter weight_filler
optional EltwiseOp operation
optional uint32 num_output
optional ReLUParameter relu_param
optional ReshapeParameter reshape_param
optional PowerParameter power_param
optional ConvolutionParameter convolution_param
optional BatchNormParameter batch_norm_param
optional ConcatParameter concat_param
optional InnerProductParameter inner_product_param
optional SoftmaxParameter softmax_param
optional DetectionOutputSSDParameter detection_output_ssd_param
optional DFMBPSROIAlignParameter dfmb_psroi_pooling_param
optional PermuteParameter permute_param
optional BBoxRegParameter bbox_reg_param
optional EltwiseParameter eltwise_param
optional PoolingParameter pooling_param
optional PaddingParameter padding_param
optional ArgMaxParameter argmax_param
optional SliceParameter slice_param
repeated LayerParameter layer
optional RoundMode round_mode
optional float negative_slope