forked from ledaiduongvnth/nvinfer-custom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnvdsinfer_model_builder.h
410 lines (342 loc) · 13.1 KB
/
nvdsinfer_model_builder.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA Corporation is strictly prohibited.
*
*/
#ifndef __NVDSINFER_MODEL_BUILDER_H__
#define __NVDSINFER_MODEL_BUILDER_H__
#include <stdarg.h>
#include <algorithm>
#include <condition_variable>
#include <map>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <NvCaffeParser.h>
#include <NvInfer.h>
#include <NvInferRuntime.h>
#include <NvOnnxParser.h>
#include <nvdsinfer_custom_impl.h>
#include "nvdsinfer_func_utils.h"
#include "nvdsinfer_tlt.h"
/* This file provides APIs for building models from Caffe/UFF/ONNX files. It
* also defines an interface where users can provide custom model parsers for
* custom networks. A helper class (TrtEngine) written on top of TensorRT's
* nvinfer1::ICudaEngine is also defined in this file.
*
* These interfaces/APIs are used by NvDsInferContextImpl class. */
namespace nvdsinfer {
using NvDsInferCudaEngineGetFcnDeprecated = decltype(&NvDsInferCudaEngineGet);
static const size_t kWorkSpaceSize = 450 * 1024 * 1024; // 450MB
/**
* ModelParser base. Any model parser implementation must inherit from the
* IModelParser interface.
*/
class BaseModelParser : public IModelParser
{
public:
BaseModelParser(const NvDsInferContextInitParams& params,
const std::shared_ptr<DlLibHandle>& dllib)
: m_ModelParams(params), m_LibHandle(dllib) {}
virtual ~BaseModelParser() {}
virtual bool isValid() const = 0;
private:
DISABLE_CLASS_COPY(BaseModelParser);
protected:
NvDsInferContextInitParams m_ModelParams;
std::shared_ptr<DlLibHandle> m_LibHandle;
};
/**
* Implementation of ModelParser for caffemodels derived from BaseModelParser.
* Manages resources internally required for parsing caffemodels.
*/
class CaffeModelParser : public BaseModelParser
{
public:
CaffeModelParser(const NvDsInferContextInitParams& initParams,
const std::shared_ptr<DlLibHandle>& handle = nullptr);
~CaffeModelParser() override;
bool isValid() const override { return m_CaffeParser.get(); }
const char* getModelName() const override { return m_ModelPath.c_str(); }
bool hasFullDimsSupported() const override { return true; }
NvDsInferStatus parseModel(nvinfer1::INetworkDefinition& network) override;
private:
NvDsInferStatus setPluginFactory();
private:
std::string m_ProtoPath;
std::string m_ModelPath;
std::vector<std::string> m_OutputLayers;
NvDsInferPluginFactoryCaffe m_CaffePluginFactory{nullptr};
UniquePtrWDestroy<nvcaffeparser1::ICaffeParser> m_CaffeParser;
};
/**
* Implementation of ModelParser for UFF models derived from BaseModelParser.
* Manages resources internally required for parsing UFF models.
*/
class UffModelParser : public BaseModelParser
{
public:
struct ModelParams
{
std::string uffFilePath;
nvuffparser::UffInputOrder inputOrder;
std::vector<std::string> inputNames;
std::vector<nvinfer1::Dims> inputDims;
std::vector<std::string> outputNames;
};
public:
UffModelParser(const NvDsInferContextInitParams& initParams,
const std::shared_ptr<DlLibHandle>& handle = nullptr);
~UffModelParser() override;
NvDsInferStatus parseModel(nvinfer1::INetworkDefinition& network) override;
bool isValid() const override { return m_UffParser.get(); }
const char* getModelName() const override
{
return m_ModelParams.uffFilePath.c_str();
}
bool hasFullDimsSupported() const override { return false; }
protected:
NvDsInferStatus initParser();
private:
NvDsInferStatus setPluginFactory();
protected:
ModelParams m_ModelParams;
NvDsInferPluginFactoryUff m_UffPluginFactory{nullptr};
UniquePtrWDestroy<nvuffparser::IUffParser> m_UffParser;
};
/**
* Implementation of ModelParser for ONNX models derived from BaseModelParser.
* Manages resources internally required for parsing ONNX models.
*/
class OnnxModelParser : public BaseModelParser
{
public:
OnnxModelParser(const NvDsInferContextInitParams& initParams,
const std::shared_ptr<DlLibHandle>& handle = nullptr)
: BaseModelParser(initParams, handle),
m_ModelName(initParams.onnxFilePath) {}
~OnnxModelParser() override = default;
bool isValid() const override { return !m_ModelName.empty(); }
const char* getModelName() const override { return m_ModelName.c_str(); }
NvDsInferStatus parseModel(nvinfer1::INetworkDefinition& network) override;
bool hasFullDimsSupported() const override { return true; }
private:
std::string m_ModelName;
UniquePtrWDestroy<nvonnxparser::IParser> m_OnnxParser;
};
/**
* Implementation of ModelParser for custom models. This implementation will look
* for the function symbol "NvDsInferCreateModelParser" in the custom library
* handle passed to it. It will call the NvDsInferCreateModelParser to get
* an instance of the IModelParser implementation required to parse the user's
* custom model.
*/
class CustomModelParser : public BaseModelParser
{
public:
CustomModelParser(const NvDsInferContextInitParams& initParams,
const std::shared_ptr<DlLibHandle>& handle);
~CustomModelParser() {};
bool isValid() const override
{
return (bool)m_CustomParser;
}
const char* getModelName() const override
{
return isValid() ? safeStr(m_CustomParser->getModelName()) : "";
}
NvDsInferStatus parseModel(nvinfer1::INetworkDefinition& network) override;
bool hasFullDimsSupported() const override
{
return m_CustomParser->hasFullDimsSupported();
}
private:
std::unique_ptr<IModelParser> m_CustomParser;
};
/** Forward declaration of TrtModelBuilder class. */
class TrtModelBuilder;
/**
* Holds build parameters common to implicit batch dimension/full dimension
* networks.
*/
struct BuildParams
{
using TensorIOFormat =
std::tuple<nvinfer1::DataType, nvinfer1::TensorFormats>;
size_t workspaceSize = kWorkSpaceSize;
NvDsInferNetworkMode networkMode = NvDsInferNetworkMode_FP32;
std::string int8CalibrationFilePath;
int dlaCore = -1;
std::vector<TensorIOFormat> inputFormats;
std::vector<TensorIOFormat> outputFormats;
public:
virtual ~BuildParams(){};
virtual NvDsInferStatus configBuilder(TrtModelBuilder& builder) = 0;
virtual bool sanityCheck() const;
};
/**
* Holds build parameters required for implicit batch dimension network.
*/
struct ImplicitBuildParams : public BuildParams
{
int maxBatchSize = 0;
std::vector<nvinfer1::Dims> inputDims;
private:
NvDsInferStatus configBuilder(TrtModelBuilder& builder) override;
bool sanityCheck() const override;
};
using ProfileDims = std::array<nvinfer1::Dims,
nvinfer1::EnumMax<nvinfer1::OptProfileSelector>()>;
/**
* Holds build parameters required for full dimensions network.
*/
struct ExplicitBuildParams : public BuildParams
{
// profileSelector, dims without batchSize
// each input must have 3 selector MIN/OPT/MAX for profile0,
// doesn't support multiple profiles
std::vector<ProfileDims> inputProfileDims;
int minBatchSize = 1;
int optBatchSize = 1;
int maxBatchSize = 1;
private:
NvDsInferStatus configBuilder(TrtModelBuilder& builder) override;
bool sanityCheck() const override;
};
/**
* Helper class written on top of nvinfer1::ICudaEngine.
*/
class TrtEngine
{
public:
TrtEngine(UniquePtrWDestroy<nvinfer1::ICudaEngine>&& engine, int dlaCore = -1)
: m_Engine(std::move(engine)), m_DlaCore(dlaCore) {}
TrtEngine(UniquePtrWDestroy<nvinfer1::ICudaEngine>&& engine,
const SharedPtrWDestroy<nvinfer1::IRuntime>& runtime, int dlaCore = -1,
const std::shared_ptr<DlLibHandle>& dlHandle = nullptr,
nvinfer1::IPluginFactory* pluginFactory = nullptr);
~TrtEngine();
bool hasDla() const { return m_DlaCore >= 0; }
int getDlaCore() const { return m_DlaCore; }
NvDsInferStatus getImplicitLayersInfo(
std::vector<NvDsInferBatchDimsLayerInfo>& layersInfo);
NvDsInferStatus getFullDimsLayersInfo(
int profileIdx, std::vector<NvDsInferBatchDimsLayerInfo>& layersInfo);
NvDsInferStatus getLayerInfo(int idx, NvDsInferLayerInfo& layer);
void printEngineInfo();
nvinfer1::ICudaEngine& engine()
{
assert(m_Engine);
return *m_Engine;
}
nvinfer1::ICudaEngine* operator->()
{
assert(m_Engine);
return m_Engine.get();
}
private:
DISABLE_CLASS_COPY(TrtEngine);
SharedPtrWDestroy<nvinfer1::IRuntime> m_Runtime;
UniquePtrWDestroy<nvinfer1::ICudaEngine> m_Engine;
std::shared_ptr<DlLibHandle> m_DlHandle;
nvinfer1::IPluginFactory* m_RuntimePluginFactory = nullptr;
int m_DlaCore = -1;
friend bool ::NvDsInferCudaEngineGetFromTltModel( nvinfer1::IBuilder * const builder,
const NvDsInferContextInitParams * const initParams,
nvinfer1::DataType dataType,
nvinfer1::ICudaEngine *& cudaEngine);
};
/**
* Helper class to build models and generate the TensorRT ICudaEngine required
* for inference. This class will parse models using the nvdsinfer::IModelParser
* interface and then build the model engine using nvinfer1::IBuilder's
* BuilderConfig APIs based on initialization parameters passed to
* NvDsInferContext. Alternatively, this class can also deserialize an existing
* serialized engine to generate the ICudaEngine.
*/
class TrtModelBuilder
{
public:
TrtModelBuilder(int gpuId, nvinfer1::ILogger& logger,
const std::shared_ptr<DlLibHandle>& dlHandle = nullptr);
~TrtModelBuilder() {}
void setInt8Calibrator(std::unique_ptr<nvinfer1::IInt8Calibrator>&& calibrator)
{
m_Int8Calibrator = std::move(calibrator);
}
/* Populate INetworkDefinition by parsing the model, build the engine and
* return it as TrtEngine instance. Also, returns a suggested path for
* writing the serialized engine to.
*
* Suggested path has the following format:
* suggested path = [modelName]_b[#batchSize]_[#device]_[#dataType].engine
*/
std::unique_ptr<TrtEngine> buildModel(
const NvDsInferContextInitParams& initParams,
std::string& suggestedPathName);
/* Builds the engine from an already populated INetworkDefinition based on
* the BuildParams passed to it. Returns the engine in the form of TrtEngine
* instance.
*/
std::unique_ptr<TrtEngine> buildEngine(
nvinfer1::INetworkDefinition& network, BuildParams& options);
/* Serialize engine to file
*/
NvDsInferStatus serializeEngine(
const std::string& path, nvinfer1::ICudaEngine& engine);
/* Deserialize engine from file
*/
std::unique_ptr<TrtEngine> deserializeEngine(
const std::string& path, int dla = -1);
private:
/* Parses a model file using an IModelParser implementation for
* Caffe/UFF/ONNX formats or from custom IModelParser implementation.
*/
NvDsInferStatus buildNetwork(const NvDsInferContextInitParams& initParams);
/* build cudaEngine from Netwwork, be careful for implicitBatch and
* explicitBatch.
*/
std::unique_ptr<TrtEngine> buildEngine();
/* Calls a custom library's implementaion of NvDsInferCudaEngineGet function
* to get a built ICudaEngine. */
std::unique_ptr<TrtEngine> getCudaEngineFromCustomLib(
NvDsInferCudaEngineGetFcnDeprecated cudaEngineGetDeprecatedFcn,
NvDsInferEngineCreateCustomFunc cudaEngineGetFcn,
const NvDsInferContextInitParams& initParams,
NvDsInferNetworkMode &networkMode);
/* config builder options */
NvDsInferStatus configCommonOptions(BuildParams& params);
NvDsInferStatus configImplicitOptions(ImplicitBuildParams& params);
NvDsInferStatus configExplicitOptions(ExplicitBuildParams& params);
std::unique_ptr<BuildParams> createImplicitParams(
const NvDsInferContextInitParams& initParams);
std::unique_ptr<BuildParams> createDynamicParams(
const NvDsInferContextInitParams& initParams);
void initCommonParams(
BuildParams& params, const NvDsInferContextInitParams& initParams);
DISABLE_CLASS_COPY(TrtModelBuilder);
int m_GpuId = 0;
nvinfer1::ILogger& m_Logger;
std::shared_ptr<DlLibHandle> m_DlLib;
std::shared_ptr<BaseModelParser> m_Parser;
std::unique_ptr<BuildParams> m_Options;
UniquePtrWDestroy<nvinfer1::IBuilder> m_Builder;
UniquePtrWDestroy<nvinfer1::IBuilderConfig> m_BuilderConfig;
UniquePtrWDestroy<nvinfer1::INetworkDefinition> m_Network;
std::shared_ptr<nvinfer1::IInt8Calibrator> m_Int8Calibrator;
friend class BuildParams;
friend class ImplicitBuildParams;
friend class ExplicitBuildParams;
friend bool ::NvDsInferCudaEngineGetFromTltModel( nvinfer1::IBuilder * const builder,
const NvDsInferContextInitParams * const initParams,
nvinfer1::DataType dataType,
nvinfer1::ICudaEngine *& cudaEngine);
};
} // end of namespace nvdsinfer
#endif