Apollo 11.0
自动驾驶开放平台
apollo::perception::inference::MultiBatchInference类 参考

#include <onnx_multi_batch_infer.h>

类 apollo::perception::inference::MultiBatchInference 继承关系图:
apollo::perception::inference::MultiBatchInference 的协作图:

Public 成员函数

 MultiBatchInference ()
 
virtual ~MultiBatchInference ()
 
bool OnnxToTRTModel (const std::string &model_file)
 Convert ONNX to TensorRT model
 
void SetOnnxOptimizationProfile (nvinfer1::IOptimizationProfile *profile, const BlobMap &input_shapes)
 
void inference ()
 
bool LoadCache (const std::string &path)
 
bool Init (const std::map< std::string, std::vector< int > > &shapes) override
 
void Infer () override
 
void init_blob (std::vector< std::string > *names)
 
base::BlobPtr< float > get_blob (const std::string &name) override
 
void FileInit ()
 
void SetStream (cudaStream_t stream)
 
- Public 成员函数 继承自 apollo::perception::inference::Inference
 Inference ()=default
 
virtual ~Inference ()=default
 
void set_max_batch_size (const int &batch_size)
 
void set_gpu_id (const int &gpu_id)
 
void set_model_info (const std::string &proto_file, const std::vector< std::string > &net_input_names, const std::vector< std::string > &net_output_names)
 

额外继承的成员函数

- Protected 属性 继承自 apollo::perception::inference::Inference
int max_batch_size_ = 1
 
int gpu_id_ = 0
 
std::string proto_file_ = ""
 
std::vector< std::string > net_output_names_
 
std::vector< std::string > net_input_names_
 

详细描述

在文件 onnx_multi_batch_infer.h 第 41 行定义.

构造及析构函数说明

◆ MultiBatchInference()

apollo::perception::inference::MultiBatchInference::MultiBatchInference ( )
inline

在文件 onnx_multi_batch_infer.h 第 43 行定义.

43{}

◆ ~MultiBatchInference()

apollo::perception::inference::MultiBatchInference::~MultiBatchInference ( )
virtual

在文件 onnx_multi_batch_infer.cc 第 92 行定义.

92 {
93 if (network_) {
94 network_->destroy();
95 }
96 if (builder_) {
97 builder_->destroy();
98 }
99 if (context_) {
100 context_->destroy();
101 }
102 if (engine_) {
103 engine_->destroy();
104 }
105}

成员函数说明

◆ FileInit()

void apollo::perception::inference::MultiBatchInference::FileInit ( )

在文件 onnx_multi_batch_infer.cc 第 116 行定义.

116 {
117 model_file_ = proto_file_;
118 output_names_ = net_output_names_;
119 input_names_ = net_input_names_;
120}
std::vector< std::string > net_input_names_
Definition inference.h:68
std::vector< std::string > net_output_names_
Definition inference.h:67

◆ get_blob()

base::BlobPtr< float > apollo::perception::inference::MultiBatchInference::get_blob ( const std::string &  name)
overridevirtual

实现了 apollo::perception::inference::Inference.

在文件 onnx_multi_batch_infer.cc 第 84 行定义.

84 {
85 auto iter = blobs_.find(name);
86 if (iter == blobs_.end()) {
87 return nullptr;
88 }
89 return iter->second;
90}

◆ Infer()

void apollo::perception::inference::MultiBatchInference::Infer ( )
overridevirtual

实现了 apollo::perception::inference::Inference.

在文件 onnx_multi_batch_infer.cc 第 295 行定义.

295 {
296 BASE_GPU_CHECK(cudaSetDevice(gpu_id_));
297 BASE_GPU_CHECK(cudaStreamSynchronize(stream_));
298 CHECK(input_names_.size() > 0 && blobs_.size() > 0);
299 auto input_shape = blobs_[input_names_[0]]->shape();
300 kBatchSize = input_shape[0];
301 if (kBatchSize == 0) {
302 AINFO << "batch size is zero.";
303 return;
304 }
305
306 int batch_size = max_batch_size_;
307
308 // binding input blob
309 for (auto name : input_names_) {
310 auto blob = get_blob(name);
311 if (blob != nullptr) {
312 int32_t index = engine_->getBindingIndex(name.c_str());
313 // careful about this line
314 // batch_size = std::min<int>(batch_size, blob->shape(0));
315 batch_size = blob->shape(0);
316 // set buffer
317 buffers_[index] = const_cast<float*>(blob->gpu_data());
318
319 // set Dim
320 nvinfer1::Dims dims = network_->getInput(index)->getDimensions();
321 dims.d[0] = batch_size;
322 context_->setOptimizationProfile(0);
323 context_->setBindingDimensions(index, dims);
324 }
325 }
326
327 // bingding output blob
328 for (auto name : output_names_) {
329 auto blob = get_blob(name);
330 if (blob != nullptr) {
331 blob->mutable_gpu_data();
332 int32_t index = engine_->getBindingIndex(name.c_str());
333 buffers_[index] = blob->mutable_gpu_data();
334 }
335 }
336
337 {
338 std::lock_guard<std::mutex> lock(mutex_);
339 context_->enqueueV2(&buffers_[0], stream_, nullptr);
340 }
341
342 BASE_GPU_CHECK(cudaStreamSynchronize(stream_));
343 for (auto name : output_names_) {
344 auto blob = get_blob(name);
345 if (blob != nullptr) {
346 blob->mutable_gpu_data();
347 }
348 }
349}
base::BlobPtr< float > get_blob(const std::string &name) override
#define AINFO
Definition log.h:42

◆ inference()

void apollo::perception::inference::MultiBatchInference::inference ( )

在文件 onnx_multi_batch_infer.cc 第 278 行定义.

278 {
279 AINFO << "Do Inference";
280}

◆ Init()

bool apollo::perception::inference::MultiBatchInference::Init ( const std::map< std::string, std::vector< int > > &  shapes)
overridevirtual

实现了 apollo::perception::inference::Inference.

在文件 onnx_multi_batch_infer.cc 第 122 行定义.

122 {
123 BASE_GPU_CHECK(cudaSetDevice(gpu_id_));
124 BASE_GPU_CHECK(cudaStreamCreate(&stream_));
125
126 FileInit();
127
128 // create a TensorRT model from the onnx model and load it into an engine
129 OnnxToTRTModel(model_file_);
130
131 if (engine_ == nullptr) {
132 AERROR << "Fail to load obstacle ONNX model";
133 return false;
134 }
135
136 // create execution context from the engine
137 context_ = engine_->createExecutionContext();
138 if (context_ == nullptr) {
139 AERROR << "Fail to create Exceution Context";
140 return false;
141 }
142 for (const auto& name : output_names_) {
143 auto iter = shapes.find(name);
144 if (iter != shapes.end()) {
145 auto blob = std::make_shared<Blob<float>>(iter->second);
146 blobs_.emplace(name, blob);
147 }
148 }
149
150 for (const auto& name : input_names_) {
151 auto iter = shapes.find(name);
152 if (iter != shapes.end()) {
153 auto blob = std::make_shared<Blob<float>>(iter->second);
154 blobs_.emplace(name, blob);
155 }
156 }
157 buffers_.resize(input_names_.size() + output_names_.size());
158
159 // init_blob(&input_names_);
160 // init_blob(&output_names_);
161
162 return true;
163}
bool OnnxToTRTModel(const std::string &model_file)
Convert ONNX to TensorRT model
#define AERROR
Definition log.h:44

◆ init_blob()

void apollo::perception::inference::MultiBatchInference::init_blob ( std::vector< std::string > *  names)

在文件 onnx_multi_batch_infer.cc 第 282 行定义.

282 {
283 for (auto name : *names) {
284 auto blob = get_blob(name);
285
286 std::vector<int> shape(blob->shape().begin(), blob->shape().end());
287 blob.reset(new apollo::perception::base::Blob<float>(shape));
288
289 buffers_[bindingIndex_] = blob->mutable_gpu_data();
290
291 bindingIndex_ += 1;
292 }
293}
A wrapper around SyncedMemory holders serving as the basic computational unit for images,...
Definition blob.h:88

◆ LoadCache()

bool apollo::perception::inference::MultiBatchInference::LoadCache ( const std::string &  path)

在文件 onnx_multi_batch_infer.cc 第 107 行定义.

107 {
108 struct stat buffer;
109 if (stat(path.c_str(), &buffer) != 0) {
110 AERROR << "[INFO] cannot find model cache : " << path << ", it will take minutes to generate...";
111 return false;
112 }
113 return true;
114}

◆ OnnxToTRTModel()

bool apollo::perception::inference::MultiBatchInference::OnnxToTRTModel ( const std::string &  model_file)

Convert ONNX to TensorRT model

参数
[in]model_fileONNX model file path

Load ONNX model, and convert it to TensorRT model

在文件 onnx_multi_batch_infer.cc 第 207 行定义.

207 {
208 if (gpu_id_ < 0) {
209 AERROR << "must use gpu mode";
210 return false;
211 }
212 // create the builder
213 builder_ = nvinfer1::createInferBuilder(onnx_gLogger);
214 network_ = builder_->createNetworkV2(
215 1U << static_cast<int>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH));
216
217 // parse onnx model
218 nvonnxparser::IParser* parser = nvonnxparser::createParser(*network_, onnx_gLogger.getTRTLogger());
219
220 const char* onnx_filename = model_file.c_str();
221 int verbosity = static_cast<int>(onnx_gLogger.getReportableSeverity());
222 if (!parser->parseFromFile(onnx_filename, verbosity)) {
223 AERROR << "Failure while parsing ONNX file: " << onnx_filename;
224 return false;
225 }
226
227 // Build the engine
228 builder_->setMaxBatchSize(max_batch_size_);
229 nvinfer1::IBuilderConfig* config = builder_->createBuilderConfig();
230 config->setMaxWorkspaceSize(1 << 30);
231 bool use_fp16 = builder_->platformHasFastFp16();
232 if (use_fp16) {
233 config->setFlag(nvinfer1::BuilderFlag::kFP16);
234 }
235 config->setFlag(nvinfer1::BuilderFlag::kDEBUG);
236
237 auto trt_cache_path = model_file + ".trt.engine";
238
239 if (!LoadCache(trt_cache_path)) {
240 nvinfer1::IOptimizationProfile* profile = builder_->createOptimizationProfile();
241 SetOnnxOptimizationProfile(profile, blobs_);
242 config->addOptimizationProfile(profile);
243
244 engine_ = builder_->buildEngineWithConfig(*network_, *config);
245 nvinfer1::IHostMemory* ser_mem = engine_->serialize();
246
247 if (ser_mem) {
248 nvinfer1::IHostMemory* serialized_model(ser_mem);
249 std::ofstream f(trt_cache_path, std::ios::binary);
250
251 f.write(reinterpret_cast<char*>(serialized_model->data()), serialized_model->size());
252 serialized_model->destroy();
253 }
254 } else {
255 AINFO << "Loading TensorRT engine from serialized model file...";
256 std::ifstream planFile(trt_cache_path);
257
258 if (!planFile.is_open()) {
259 AERROR << "Could not open serialized model";
260 return false;
261 }
262 initLibNvInferPlugins(&onnx_gLogger, "");
263
264 AINFO << "success open serialized model";
265 std::stringstream planBuffer;
266 planBuffer << planFile.rdbuf();
267 std::string plan = planBuffer.str();
268 nvinfer1::IRuntime* runtime = nvinfer1::createInferRuntime(onnx_gLogger);
269
270 engine_ = runtime->deserializeCudaEngine(static_cast<const void*>(plan.data()), plan.size(), nullptr);
271 runtime->destroy();
272 }
273 config->destroy();
274 parser->destroy();
275 return true;
276}
double f
nvinfer1::ILogger & getTRTLogger()
Severity getReportableSeverity() const
void SetOnnxOptimizationProfile(nvinfer1::IOptimizationProfile *profile, const BlobMap &input_shapes)
OnnxLogger onnx_gLogger

◆ SetOnnxOptimizationProfile()

void apollo::perception::inference::MultiBatchInference::SetOnnxOptimizationProfile ( nvinfer1::IOptimizationProfile *  profile,
const BlobMap &  input_shapes 
)

在文件 onnx_multi_batch_infer.cc 第 165 行定义.

167 {
168 // Optimizat every input
169 // TODO(huanglei14) Distinguish inputs that do not require optimization
170 for (int i = 0; i < network_->getNbInputs(); ++i) {
171 nvinfer1::ITensor* nv_input = network_->getInput(i);
172 const char* nv_input_name = nv_input->getName();
173 nvinfer1::Dims nv_input_dims = nv_input->getDimensions();
174 auto it = input_shapes.find(nv_input_name);
175 if (it != input_shapes.end()) {
176 CHECK_EQ(nv_input_dims.nbDims, input_shapes.at(nv_input_name)->num_axes());
177 }
178 AINFO << "nv_input_name: " << nv_input_name;
179 AINFO << "nv_input_dims: ";
180 AINFO << "\t" << nv_input_dims.d[0];
181 if (nv_input_dims.d[0] > 0) {
182 continue;
183 }
184
185 for (int j = 1; j < nv_input_dims.nbDims; ++j) {
186 AINFO << "\t" << nv_input_dims.d[j];
187 if (it != input_shapes.end()) {
188 // input dims should be dynamic, or equal to those specified by init
189 // options
190 CHECK(nv_input_dims.d[j] < 0 || nv_input_dims.d[j] == it->second->shape(j));
191 nv_input_dims.d[j] = it->second->shape(j);
192 } else {
193 // input should have fixed dims if not specfied by init options
194 CHECK(nv_input_dims.d[j] > 0);
195 }
196 }
197
198 nv_input_dims.d[0] = 1;
199 profile->setDimensions(nv_input_name, nvinfer1::OptProfileSelector::kMIN, nv_input_dims);
200 nv_input_dims.d[0] = std::max(1, static_cast<int>(max_batch_size_ / 2));
201 profile->setDimensions(nv_input_name, nvinfer1::OptProfileSelector::kOPT, nv_input_dims);
202 nv_input_dims.d[0] = max_batch_size_;
203 profile->setDimensions(nv_input_name, nvinfer1::OptProfileSelector::kMAX, nv_input_dims);
204 }
205}

◆ SetStream()

void apollo::perception::inference::MultiBatchInference::SetStream ( cudaStream_t  stream)
inlinevirtual

重载 apollo::perception::inference::Inference .

在文件 onnx_multi_batch_infer.h 第 65 行定义.

65 {
66 stream_ = stream;
67 }

该类的文档由以下文件生成: