16#ifdef NV_TENSORRT_MAJOR
17#if NV_TENSORRT_MAJOR == 8
26#include <cuda_runtime_api.h>
28#include "absl/strings/str_cat.h"
33#if GPU_PLATFORM == NVIDIA
36 void log(Severity severity,
const char* msg)
noexcept override {
38 case Severity::kINTERNAL_ERROR:
39 case Severity::kERROR:
42 case Severity::kWARNING:
46 case Severity::kVERBOSE:
54#elif GPU_PLATFORM == AMD
59class IExecutionContext {};
69#define GPU_CHECK(ans) \
70 { GPUAssert((ans), __FILE__, __LINE__); }
71inline void GPUAssert(cudaError_t code,
const char* file,
int line,
73 if (code != cudaSuccess) {
74 fprintf(stderr,
"GPUassert: %s %s %d\n", cudaGetErrorString(code), file,
76 if (abort) exit(code);
81 auto iter = blobs_.find(name);
82 if (iter == blobs_.end()) {
89 const std::string& model_file,
const float score_threshold,
90 const std::vector<std::string>& outputs,
91 const std::vector<std::string>& inputs)
92 : model_file_(model_file),
93 score_threshold_(score_threshold),
94 output_names_(outputs),
95 input_names_(inputs) {}
98 const std::string& model_file,
const std::vector<std::string>& outputs,
99 const std::vector<std::string>& inputs)
100 : model_file_(model_file), output_names_(outputs), input_names_(inputs) {}
104bool SingleBatchInference::LoadCache(
const std::string& path) {
106 if (stat(path.c_str(), &buffer) != 0) {
107 AERROR <<
"[INFO] cannot find model cache : " << path
108 <<
", it will take minutes to generate...";
115 const std::map<std::string, std::vector<int>>& shapes) {
116 BASE_GPU_CHECK(cudaSetDevice(
gpu_id_));
117 BASE_GPU_CHECK(cudaStreamCreate(&stream_));
120 OnnxToTRTModel(model_file_);
122 if (engine_ ==
nullptr) {
123 AERROR <<
"Fail to load obstacle ONNX model";
128#if GPU_PLATFORM == NVIDIA
129 context_ = engine_->createExecutionContext();
130 if (context_ ==
nullptr) {
131 AERROR <<
"Fail to create Exceution Context";
135 for (
const auto& name : output_names_) {
136 auto iter = shapes.find(name);
137 if (iter != shapes.end()) {
138 auto blob = std::make_shared<Blob<float>>(iter->second);
139 blobs_.emplace(name, blob);
143 for (
const auto& name : input_names_) {
144 auto iter = shapes.find(name);
145 if (iter != shapes.end()) {
146 auto blob = std::make_shared<Blob<float>>(iter->second);
147 blobs_.emplace(name, blob);
150 buffers_.resize(input_names_.size() + output_names_.size());
152 init_blob(&input_names_);
153 init_blob(&output_names_);
155#elif GPU_PLATFORM == AMD
156 assert(0 &&
"OnnxObstacleDetector::Init() is not implemented yet");
161bool SingleBatchInference::OnnxToTRTModel(
const std::string& model_file) {
162#if GPU_PLATFORM == NVIDIA
163 int verbosity =
static_cast<int>(nvinfer1::ILogger::Severity::kVERBOSE);
167 AERROR <<
"must use gpu mode";
171 nvinfer1::IBuilder* builder = nvinfer1::createInferBuilder(
onnx_gLogger);
172 nvinfer1::INetworkDefinition* network = builder->createNetworkV2(
173 1U <<
static_cast<int>(
174 nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH));
177 nvonnxparser::IParser* parser =
180 const char* onnx_filename = model_file.c_str();
181 parser->parseFromFile(onnx_filename, verbosity);
184 builder->setMaxBatchSize(kBatchSize);
185 nvinfer1::IBuilderConfig* config = builder->createBuilderConfig();
186 bool use_fp16 = builder->platformHasFastFp16();
188 config->setFlag(nvinfer1::BuilderFlag::kFP16);
190 config->setMaxWorkspaceSize(1 << 30);
192 auto trt_cache_path = model_file +
".trt.engine";
194 if (!LoadCache(trt_cache_path)) {
195 engine_ = builder->buildEngineWithConfig(*network, *config);
197 if (engine_->serialize()) {
198 nvinfer1::IHostMemory* serialized_model(engine_->serialize());
199 std::ofstream
f(trt_cache_path, std::ios::binary);
201 f.write(
reinterpret_cast<char*
>(serialized_model->data()),
202 serialized_model->size());
203 serialized_model->destroy();
204 AERROR <<
"Saving serialized model file to " << trt_cache_path;
207 AINFO <<
"Loading TensorRT engine from serialized model file...";
208 std::ifstream planFile(trt_cache_path);
210 if (!planFile.is_open()) {
211 AERROR <<
"Could not open serialized model";
216 AINFO <<
"success open serialized model";
217 std::stringstream planBuffer;
218 planBuffer << planFile.rdbuf();
219 std::string plan = planBuffer.str();
220 nvinfer1::IRuntime* runtime = nvinfer1::createInferRuntime(
onnx_gLogger);
222 engine_ = runtime->deserializeCudaEngine(
223 static_cast<const void*
>(plan.data()), plan.size(),
nullptr);
227#elif GPU_PLATFORM == AMD
228 assert(0 &&
"OnnxObstacleDetector::OnnxToTRTModel() is not implemented yet");
232void SingleBatchInference::init_blob(std::vector<std::string>* names) {
233 for (
auto name : *names) {
236 std::vector<int> shape(blob->shape().begin(), blob->shape().end());
238 buffers_[bindingIndex_] = blob->mutable_gpu_data();
244 BASE_GPU_CHECK(cudaSetDevice(
gpu_id_));
245 BASE_GPU_CHECK(cudaStreamSynchronize(stream_));
247 for (
auto name : input_names_) {
249 if (blob !=
nullptr) {
259 for (
auto name : output_names_) {
261 if (blob !=
nullptr) {
267 std::lock_guard<std::mutex> lock(mutex_);
271 for (
auto name : output_names_) {
273 if (blob !=
nullptr) {
274 blob->mutable_gpu_data();
A wrapper around SyncedMemory holders serving as the basic computational unit for images,...
virtual ~SingleBatchInference()
base::BlobPtr< float > get_blob(const std::string &name) override
bool Init(const std::map< std::string, std::vector< int > > &shapes) override
SingleBatchInference(const std::string &model_file, const float score_threshold, const std::vector< std::string > &outputs, const std::vector< std::string > &inputs)
std::shared_ptr< Blob< Dtype > > BlobPtr