-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnvdsinfer_model_builder.cpp
1459 lines (1297 loc) · 46 KB
/
nvdsinfer_model_builder.cpp
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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.
*
*/
#include <dlfcn.h>
#include <unistd.h>
#include <array>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <NvInferPlugin.h>
#include <NvOnnxParser.h>
#include <NvUffParser.h>
#include "nvdsinfer.h"
#include "nvdsinfer_custom_impl.h"
#include "nvdsinfer_func_utils.h"
#include "nvdsinfer_model_builder.h"
#include "nvdsinfer_utils.h"
namespace nvdsinfer {
/* Default data type for bound layers - FP32 */
constexpr nvinfer1::DataType kDefaultTensorDataType = nvinfer1::DataType::kFLOAT;
/* Default tensort format for bound layers - Linear. */
constexpr nvinfer1::TensorFormats kDefaultTensorFormats =
1U << (uint32_t)nvinfer1::TensorFormat::kLINEAR;
CaffeModelParser::CaffeModelParser(const NvDsInferContextInitParams& initParams,
const std::shared_ptr<DlLibHandle>& handle)
: BaseModelParser(initParams, handle),
m_ProtoPath(initParams.protoFilePath),
m_ModelPath(initParams.modelFilePath)
{
if(initParams.numOutputLayers <= 0)
{
dsInferError("No output layers specified. Need atleast one output layer");
return;
}
for (unsigned int i = 0; i < initParams.numOutputLayers; i++)
{
assert(initParams.outputLayerNames[i]);
m_OutputLayers.emplace_back(initParams.outputLayerNames[i]);
}
m_CaffeParser = nvcaffeparser1::createCaffeParser();
}
CaffeModelParser::~CaffeModelParser()
{
m_CaffeParser.reset();
/* Destroy the PluginFactory created for building the Caffe model.*/
if (m_CaffePluginFactory.pluginFactory)
{
assert(m_LibHandle);
auto destroyFunc =
READ_SYMBOL(m_LibHandle, NvDsInferPluginFactoryCaffeDestroy);
if (destroyFunc)
{
destroyFunc(m_CaffePluginFactory);
}
else
{
dsInferWarning(
"Custom lib: %s doesn't have function "
"<NvDsInferPluginFactoryCaffeDestroy> may cause memory-leak",
safeStr(m_LibHandle->getPath()));
}
}
}
NvDsInferStatus
CaffeModelParser::setPluginFactory()
{
assert(m_CaffeParser);
if (!m_LibHandle)
return NVDSINFER_SUCCESS;
/* Check if the custom library provides a PluginFactory for Caffe parsing.
*/
auto fcn = READ_SYMBOL(m_LibHandle, NvDsInferPluginFactoryCaffeGet);
if (!fcn)
return NVDSINFER_SUCCESS;
NvDsInferPluginFactoryType type{PLUGIN_FACTORY};
if (!fcn(m_CaffePluginFactory, type))
{
dsInferError(
"Could not get PluginFactory instance for "
"Caffe parsing from custom library");
return NVDSINFER_CUSTOM_LIB_FAILED;
}
switch (type)
{
case PLUGIN_FACTORY:
m_CaffeParser->setPluginFactory(m_CaffePluginFactory.pluginFactory);
break;
case PLUGIN_FACTORY_EXT:
m_CaffeParser->setPluginFactoryExt(
m_CaffePluginFactory.pluginFactoryExt);
break;
case PLUGIN_FACTORY_V2:
m_CaffeParser->setPluginFactoryV2(m_CaffePluginFactory.pluginFactoryV2);
break;
default:
dsInferError(
"Invalid PluginFactory type returned by "
"custom library");
return NVDSINFER_CUSTOM_LIB_FAILED;
}
return NVDSINFER_SUCCESS;
}
NvDsInferStatus
CaffeModelParser::parseModel(nvinfer1::INetworkDefinition& network)
{
if (!isValid())
{
dsInferError("parse Caffe model failed, please check config file");
return NVDSINFER_INVALID_PARAMS;
}
if (!file_accessible(m_ProtoPath))
{
dsInferError("Cannot access prototxt file '%s'", safeStr(m_ProtoPath));
return NVDSINFER_CONFIG_FAILED;
}
if (!file_accessible(m_ModelPath))
{
dsInferError("Cannot access caffemodel file '%s'", safeStr(m_ModelPath));
return NVDSINFER_CONFIG_FAILED;
}
NvDsInferStatus status = setPluginFactory();
if (status != NVDSINFER_SUCCESS)
{
dsInferError("Failed to set caffe plugin Factory from custom lib");
return NVDSINFER_TENSORRT_ERROR;
}
/* Parse the caffe model. */
const nvcaffeparser1::IBlobNameToTensor* blobNameToTensor =
m_CaffeParser->parse(m_ProtoPath.c_str(), m_ModelPath.c_str(), network,
nvinfer1::DataType::kFLOAT);
if (!blobNameToTensor)
{
dsInferError("Failed while parsing caffe network: %s", safeStr(m_ProtoPath));
return NVDSINFER_TENSORRT_ERROR;
}
for (const auto& layerName : m_OutputLayers)
{
/* Find and mark output layers */
nvinfer1::ITensor* tensor = blobNameToTensor->find(layerName.c_str());
if (!tensor)
{
dsInferError("Could not find output layer '%s'", safeStr(layerName));
return NVDSINFER_CONFIG_FAILED;
}
network.markOutput(*tensor);
}
return NVDSINFER_SUCCESS;
}
UffModelParser::UffModelParser(const NvDsInferContextInitParams& initParams,
const std::shared_ptr<DlLibHandle>& handle)
: BaseModelParser(initParams, handle)
{
m_ModelParams.uffFilePath = initParams.uffFilePath;
if (string_empty(initParams.uffInputBlobName))
{
dsInferError("Uff input blob name is empty");
return;
}
if(initParams.numOutputLayers <= 0)
{
dsInferError("No output layers specified. Need atleast one output layer");
return;
}
m_ModelParams.inputNames.emplace_back(initParams.uffInputBlobName);
nvinfer1::Dims3 uffInputDims(initParams.uffDimsCHW.c,
initParams.uffDimsCHW.h, initParams.uffDimsCHW.w);
m_ModelParams.inputDims.emplace_back(uffInputDims);
if (m_ModelParams.inputDims.size() != m_ModelParams.inputNames.size())
{
dsInferError(
"Unrecognized uff input blob names and dims are not match");
return;
}
switch (initParams.uffInputOrder)
{
case NvDsInferTensorOrder_kNCHW:
m_ModelParams.inputOrder = nvuffparser::UffInputOrder::kNCHW;
break;
case NvDsInferTensorOrder_kNHWC:
m_ModelParams.inputOrder = nvuffparser::UffInputOrder::kNHWC;
break;
case NvDsInferTensorOrder_kNC:
m_ModelParams.inputOrder = nvuffparser::UffInputOrder::kNC;
break;
default:
dsInferError("Unrecognized uff input order");
m_ModelParams.inputOrder = (nvuffparser::UffInputOrder)(-1);
return;
}
for (unsigned int i = 0; i < initParams.numOutputLayers; i++)
{
assert(initParams.outputLayerNames[i]);
m_ModelParams.outputNames.emplace_back(initParams.outputLayerNames[i]);
}
m_UffParser = nvuffparser::createUffParser();
}
UffModelParser::~UffModelParser()
{
m_UffParser.reset();
if (m_UffPluginFactory.pluginFactory)
{
/* Destroy the PluginFactory created for building the Caffe model.*/
assert(m_LibHandle);
auto destroyFcn =
READ_SYMBOL(m_LibHandle, NvDsInferPluginFactoryUffDestroy);
if (destroyFcn)
{
destroyFcn(m_UffPluginFactory);
}
else
{
dsInferWarning(
"Custom lib: %s doesn't have function "
"<NvDsInferPluginFactoryUffDestroy> may cause memory-leak",
safeStr(m_LibHandle->getPath()));
}
}
}
NvDsInferStatus
UffModelParser::setPluginFactory()
{
assert(m_UffParser);
if (!m_LibHandle)
return NVDSINFER_SUCCESS;
/* Check if the custom library provides a PluginFactory for UFF parsing. */
auto fcn = READ_SYMBOL(m_LibHandle, NvDsInferPluginFactoryUffGet);
if (!fcn)
return NVDSINFER_SUCCESS;
NvDsInferPluginFactoryType type{PLUGIN_FACTORY};
if (!fcn(m_UffPluginFactory, type))
{
dsInferError(
"Could not get PluginFactory instance for "
"Uff parsing from custom library");
return NVDSINFER_CUSTOM_LIB_FAILED;
}
/* Use the appropriate API to set the PluginFactory based on its
* type. */
switch (type)
{
case PLUGIN_FACTORY:
m_UffParser->setPluginFactory(m_UffPluginFactory.pluginFactory);
break;
case PLUGIN_FACTORY_EXT:
m_UffParser->setPluginFactoryExt(m_UffPluginFactory.pluginFactoryExt);
break;
default:
dsInferError(
"Invalid PluginFactory type returned by "
"custom library: %s",
safeStr(m_LibHandle->getPath()));
return NVDSINFER_CUSTOM_LIB_FAILED;
}
return NVDSINFER_SUCCESS;
}
NvDsInferStatus
UffModelParser::initParser()
{
/* Check if the custom library provides a PluginFactory for UFF parsing. */
NvDsInferStatus status = setPluginFactory();
if (status != NVDSINFER_SUCCESS)
{
dsInferError("Failed to set UFF plugin Factory from custom lib");
return NVDSINFER_TENSORRT_ERROR;
}
/* Register the input layer (name, dims and input order). */
for (size_t i = 0; i < m_ModelParams.inputNames.size(); ++i)
{
if (!m_UffParser->registerInput(m_ModelParams.inputNames[i].c_str(),
m_ModelParams.inputDims[i], m_ModelParams.inputOrder))
{
dsInferError(
"Failed to register uff input blob: %s DimsCHW:(%s) "
"Order: %s",
safeStr(m_ModelParams.inputNames[i]),
safeStr(dims2Str(m_ModelParams.inputDims[i])),
(int)m_ModelParams.inputOrder);
return NVDSINFER_CONFIG_FAILED;
}
}
/* Register outputs. */
for (const auto& layerName : m_ModelParams.outputNames)
{
if (!m_UffParser->registerOutput(layerName.c_str()))
{
dsInferError(
"Failed to register uff output blob: %s", safeStr(layerName));
return NVDSINFER_CONFIG_FAILED;
}
}
return NVDSINFER_SUCCESS;
}
NvDsInferStatus
UffModelParser::parseModel(nvinfer1::INetworkDefinition& network)
{
if (!isValid())
{
dsInferError("parse Uff model failed, please check config file");
return NVDSINFER_INVALID_PARAMS;
}
NvDsInferStatus status = initParser();
if (status != NVDSINFER_SUCCESS)
{
dsInferError("Failed to init uff parser for file: %s",
safeStr(m_ModelParams.uffFilePath));
return status;
}
if (!file_accessible(m_ModelParams.uffFilePath))
{
dsInferError(
"Cannot access UFF file '%s'", safeStr(m_ModelParams.uffFilePath));
return NVDSINFER_CONFIG_FAILED;
}
if (!m_UffParser->parse(m_ModelParams.uffFilePath.c_str(), network,
nvinfer1::DataType::kFLOAT))
{
dsInferError(
"Failed to parse UFF file: %s, incorrect file or incorrect"
" input/output blob names",
safeStr(m_ModelParams.uffFilePath));
return NVDSINFER_TENSORRT_ERROR;
}
return NVDSINFER_SUCCESS;
}
NvDsInferStatus
OnnxModelParser::parseModel(nvinfer1::INetworkDefinition& network)
{
if (!file_accessible(m_ModelName.c_str()))
{
dsInferError("Cannot access ONNX file '%s'", safeStr(m_ModelName));
return NVDSINFER_CONFIG_FAILED;
}
m_OnnxParser = nvonnxparser::createParser(network, *gTrtLogger);
if (!m_OnnxParser->parseFromFile(
m_ModelName.c_str(), (int)nvinfer1::ILogger::Severity::kWARNING))
{
dsInferError("Failed to parse onnx file");
return NVDSINFER_TENSORRT_ERROR;
}
return NVDSINFER_SUCCESS;
}
CustomModelParser::CustomModelParser(const NvDsInferContextInitParams& initParams,
const std::shared_ptr<DlLibHandle>& handle)
: BaseModelParser(initParams, handle)
{
assert(handle);
/* Get the address of NvDsInferCreateModelParser interface implemented by
* the custom library. */
auto createFcn = READ_SYMBOL(m_LibHandle, NvDsInferCreateModelParser);
if (!createFcn)
return;
/* Create the custom parser using NvDsInferCreateModelParser interface. */
std::unique_ptr<IModelParser> modelParser(createFcn(&initParams));
if (!modelParser)
{
dsInferError(
"Failed to create custom parser from lib:%s, model path:%s",
safeStr(handle->getPath()),
safeStr(initParams.customNetworkConfigFilePath));
}
m_CustomParser = std::move(modelParser);
}
NvDsInferStatus
CustomModelParser::parseModel(nvinfer1::INetworkDefinition& network)
{
if (!isValid())
{
dsInferError(
"Failed to parse model since parser description is not valid or "
"parser cannot be created");
return NVDSINFER_CUSTOM_LIB_FAILED;
}
return m_CustomParser->parseModel(network);
}
bool
BuildParams::sanityCheck() const
{
/* Check for supported network modes. */
switch (networkMode)
{
case NvDsInferNetworkMode_FP32:
case NvDsInferNetworkMode_FP16:
case NvDsInferNetworkMode_INT8:
break;
default:
return false;
}
return true;
}
bool
ImplicitBuildParams::sanityCheck() const
{
/* Check for valid batch size. */
if (maxBatchSize <= 0)
return false;
return BuildParams::sanityCheck();
}
NvDsInferStatus
ImplicitBuildParams::configBuilder(TrtModelBuilder& trtBuilder)
{
return trtBuilder.configImplicitOptions(*this);
}
bool
ExplicitBuildParams::sanityCheck() const
{
/* Check that min <= opt <= max batch size. */
if (minBatchSize > optBatchSize || optBatchSize > maxBatchSize)
return false;
for (auto& layer : inputProfileDims)
{
int nd = -1;
if (!std::all_of(
layer.begin(), layer.end(), [&nd](const nvinfer1::Dims& s) {
if (nd > 0)
return nd == s.nbDims;
nd = s.nbDims;
return true;
}))
{
dsInferError("Explicit Options sanity check failed.");
return false;
}
}
return BuildParams::sanityCheck();
}
NvDsInferStatus
ExplicitBuildParams::configBuilder(TrtModelBuilder& trtBuilder)
{
return trtBuilder.configExplicitOptions(*this);
}
TrtEngine::TrtEngine(UniquePtrWDestroy<nvinfer1::ICudaEngine>&& engine,
const SharedPtrWDestroy<nvinfer1::IRuntime>& runtime, int dlaCore,
const std::shared_ptr<DlLibHandle>& dlHandle,
nvinfer1::IPluginFactory* pluginFactory)
: m_Runtime(runtime),
m_Engine(std::move(engine)),
m_DlHandle(dlHandle),
m_RuntimePluginFactory(pluginFactory),
m_DlaCore(dlaCore){}
TrtEngine::~TrtEngine()
{
m_Engine.reset();
/* Destroy the Runtime PluginFactory instance if provided. */
if (m_RuntimePluginFactory && m_DlHandle)
{
auto destroyFcn =
READ_SYMBOL(m_DlHandle, NvDsInferPluginFactoryRuntimeDestroy);
if (!destroyFcn)
{
dsInferWarning(
"NvDsInferPluginFactoryRuntimeDestroy is missing in custom "
"lib.");
}
destroyFcn(m_RuntimePluginFactory);
}
m_Runtime.reset();
}
/* Get properties of bound layers like the name, dimension, datatype
*/
NvDsInferStatus
TrtEngine::getLayerInfo(int idx, NvDsInferLayerInfo& info)
{
assert(m_Engine);
assert(idx < m_Engine->getNbBindings());
nvinfer1::Dims d = m_Engine->getBindingDimensions(idx);
info.buffer = nullptr;
info.isInput = m_Engine->bindingIsInput(idx);
info.bindingIndex = idx;
info.layerName = safeStr(m_Engine->getBindingName(idx));
if (m_Engine->hasImplicitBatchDimension())
{
info.inferDims = trt2DsDims(d);
}
else
{
NvDsInferBatchDims batchDims;
convertFullDims(d, batchDims);
info.inferDims = batchDims.dims;
}
switch (m_Engine->getBindingDataType(idx))
{
case nvinfer1::DataType::kFLOAT:
info.dataType = FLOAT;
break;
case nvinfer1::DataType::kHALF:
info.dataType = HALF;
break;
case nvinfer1::DataType::kINT32:
info.dataType = INT32;
break;
case nvinfer1::DataType::kINT8:
info.dataType = INT8;
break;
default:
dsInferError(
"Unknown data type for bound layer i(%s)", safeStr(info.layerName));
return NVDSINFER_TENSORRT_ERROR;
}
return NVDSINFER_SUCCESS;
}
/* Get information for all layers for implicit batch dimensions network. */
NvDsInferStatus
TrtEngine::getImplicitLayersInfo(std::vector<NvDsInferBatchDimsLayerInfo>& layersInfo)
{
layersInfo.clear();
int maxBatch = m_Engine->getMaxBatchSize();
for (int i = 0; i < (int)m_Engine->getNbBindings(); i++)
{
NvDsInferBatchDimsLayerInfo layerInfo;
RETURN_NVINFER_ERROR(getLayerInfo(i, layerInfo),
"initialize backend context failed on layer: %d", i);
if (hasWildcard(layerInfo.inferDims))
{
dsInferError(
"ImplicitTrtBackend initialize failed because bindings has "
"wildcard dims");
return NVDSINFER_CONFIG_FAILED;
}
for (int iSelector = 0; iSelector < (int)kSELECTOR_SIZE; ++iSelector)
{
layerInfo.profileDims[iSelector] =
NvDsInferBatchDims{maxBatch, layerInfo.inferDims};
}
layersInfo.emplace_back(layerInfo);
}
return NVDSINFER_SUCCESS;
}
/* Get information for all layers for full dimensions network. */
NvDsInferStatus
TrtEngine::getFullDimsLayersInfo(int profileIdx,
std::vector<NvDsInferBatchDimsLayerInfo>& layersInfo)
{
layersInfo.clear();
for (int i = 0; i < (int)m_Engine->getNbBindings(); i++)
{
NvDsInferBatchDimsLayerInfo layerInfo;
RETURN_NVINFER_ERROR(getLayerInfo(i, layerInfo),
"initialize backend context failed on layer: %d", i);
if (layerInfo.isInput)
{
nvinfer1::Dims minDims = m_Engine->getProfileDimensions(
i, profileIdx, nvinfer1::OptProfileSelector::kMIN);
nvinfer1::Dims optDims = m_Engine->getProfileDimensions(
i, profileIdx, nvinfer1::OptProfileSelector::kOPT);
nvinfer1::Dims maxDims = m_Engine->getProfileDimensions(
i, profileIdx, nvinfer1::OptProfileSelector::kMAX);
assert(minDims <= optDims && optDims <= maxDims);
NvDsInferBatchDims batchDims;
convertFullDims(minDims, batchDims);
layerInfo.profileDims[kSELECTOR_MIN] = batchDims;
convertFullDims(optDims, batchDims);
layerInfo.profileDims[kSELECTOR_OPT] = batchDims;
convertFullDims(maxDims, batchDims);
layerInfo.profileDims[kSELECTOR_MAX] = batchDims;
}
layersInfo.emplace_back(layerInfo);
}
return NVDSINFER_SUCCESS;
}
/* Print engine details. */
void
TrtEngine::printEngineInfo()
{
assert(m_Engine);
nvinfer1::Dims checkDims = m_Engine->getBindingDimensions(0);
assert(m_Engine->getNbOptimizationProfiles() > 0);
std::stringstream s;
std::vector<NvDsInferBatchDimsLayerInfo> layersInfo;
bool isFullDims = false;
if (hasWildcard(checkDims))
{
isFullDims = true;
getFullDimsLayersInfo(0, layersInfo);
s << "[FullDims Engine Info]: layers num: " << layersInfo.size()
<< "\n";
}
else
{
isFullDims = false;
getImplicitLayersInfo(layersInfo);
s << "[Implicit Engine Info]: layers num: " << layersInfo.size()
<< "\n";
}
for (int i = 0; i < (int)layersInfo.size(); ++i)
{
NvDsInferBatchDimsLayerInfo& layer = layersInfo[i];
s << std::setw(3) << std::left << i << " ";
s << std::setw(6) << std::left << (layer.isInput ? "INPUT" : "OUTPUT")
<< " ";
s << std::setw(6) << std::left << dataType2Str(layer.dataType) << " ";
s << std::setw(15) << std::left << safeStr(layer.layerName) << " ";
s << std::setw(15) << std::left << dims2Str(layer.inferDims) << " ";
if (isFullDims)
{
s << "min: " << std::setw(15) << std::left
<< batchDims2Str(layer.profileDims[kSELECTOR_MIN]) << " ";
s << "opt: " << std::setw(15) << std::left
<< batchDims2Str(layer.profileDims[kSELECTOR_OPT]) << " ";
s << "Max: " << std::setw(15) << std::left
<< batchDims2Str(layer.profileDims[kSELECTOR_MAX]) << " ";
}
s << "\n";
}
dsInferInfo("%s", s.str().c_str());
}
TrtModelBuilder::TrtModelBuilder(int gpuId, nvinfer1::ILogger& logger,
const std::shared_ptr<DlLibHandle>& dlHandle)
: m_GpuId(gpuId), m_Logger(logger), m_DlLib(dlHandle)
{
m_Builder.reset(nvinfer1::createInferBuilder(logger));
assert(m_Builder);
}
/* Get already built CUDA Engine from custom library. */
std::unique_ptr<TrtEngine>
TrtModelBuilder::getCudaEngineFromCustomLib(NvDsInferCudaEngineGetFcnDeprecated cudaEngineGetDeprecatedFcn,
NvDsInferEngineCreateCustomFunc cudaEngineGetFcn,
const NvDsInferContextInitParams& initParams,
NvDsInferNetworkMode &networkMode)
{
networkMode = initParams.networkMode;
nvinfer1::DataType modelDataType;
switch (initParams.networkMode)
{
case NvDsInferNetworkMode_FP32:
case NvDsInferNetworkMode_FP16:
case NvDsInferNetworkMode_INT8:
break;
default:
dsInferError("Unknown network mode %d", networkMode);
return nullptr;
}
if (networkMode == NvDsInferNetworkMode_INT8)
{
/* Check if platform supports INT8 else use FP16 */
if (m_Builder->platformHasFastInt8())
{
if (m_Int8Calibrator != nullptr)
{
/* Set INT8 mode and set the INT8 Calibrator */
m_Builder->setInt8Mode(true);
m_Builder->setInt8Calibrator(m_Int8Calibrator.get());
/* modelDataType should be FLOAT for INT8 */
modelDataType = nvinfer1::DataType::kFLOAT;
}
else if (cudaEngineGetFcn != nullptr || cudaEngineGetDeprecatedFcn != nullptr)
{
dsInferWarning("INT8 calibration file not specified/accessible. "
"INT8 calibration can be done through setDynamicRange "
"API in 'NvDsInferCreateNetwork' implementation");
}
else
{
dsInferWarning("INT8 calibration file not specified. Trying FP16 mode.");
networkMode = NvDsInferNetworkMode_FP16;
}
}
else
{
dsInferWarning("INT8 not supported by platform. Trying FP16 mode.");
networkMode = NvDsInferNetworkMode_FP16;
}
}
if (networkMode == NvDsInferNetworkMode_FP16)
{
/* Check if platform supports FP16 else use FP32 */
if (m_Builder->platformHasFastFp16())
{
m_Builder->setHalf2Mode(true);
modelDataType = nvinfer1::DataType::kHALF;
}
else
{
dsInferWarning("FP16 not supported by platform. Using FP32 mode.");
networkMode = NvDsInferNetworkMode_FP32;
}
}
if (networkMode == NvDsInferNetworkMode_FP32)
{
modelDataType = nvinfer1::DataType::kFLOAT;
}
/* Set the maximum batch size */
m_Builder->setMaxBatchSize(initParams.maxBatchSize);
m_Builder->setMaxWorkspaceSize(kWorkSpaceSize);
int dla = -1;
/* Use DLA if specified. */
if (initParams.useDLA)
{
m_Builder->setDefaultDeviceType(nvinfer1::DeviceType::kDLA);
m_Builder->setDLACore(initParams.dlaCore);
m_Builder->allowGPUFallback(true);
dla = initParams.dlaCore;
if (networkMode == NvDsInferNetworkMode_FP32)
{
dsInferWarning("FP32 mode requested with DLA. DLA may execute "
"in FP16 mode instead.");
}
}
/* Get the cuda engine from the library */
nvinfer1::ICudaEngine *engine = nullptr;
if (cudaEngineGetFcn && (!cudaEngineGetFcn (m_Builder.get(),
(NvDsInferContextInitParams *)&initParams,
modelDataType, engine) ||
engine == nullptr))
{
dsInferError("Failed to create network using custom network creation"
" function");
return nullptr;
}
if (cudaEngineGetDeprecatedFcn && (!cudaEngineGetDeprecatedFcn (m_Builder.get(),
(NvDsInferContextInitParams *)&initParams,
modelDataType, engine) ||
engine == nullptr))
{
dsInferError("Failed to create network using custom network creation"
" function");
return nullptr;
}
return std::make_unique<TrtEngine>(UniquePtrWDestroy<nvinfer1::ICudaEngine>(engine), dla);
}
/* Build the model and return the generated engine. */
std::unique_ptr<TrtEngine>
TrtModelBuilder::buildModel(const NvDsInferContextInitParams& initParams,
std::string& suggestedPathName)
{
std::unique_ptr<TrtEngine> engine;
std::string modelPath;
NvDsInferNetworkMode networkMode;
/* check if custom library provides NvDsInferCudaEngineGet interface. */
NvDsInferEngineCreateCustomFunc cudaEngineGetFcn = nullptr;
NvDsInferCudaEngineGetFcnDeprecated cudaEngineGetDeprecatedFcn = nullptr;
if (m_DlLib && !string_empty(initParams.customEngineCreateFuncName))
{
cudaEngineGetFcn = m_DlLib->symbol<NvDsInferEngineCreateCustomFunc>(
initParams.customEngineCreateFuncName);
if (!cudaEngineGetFcn)
{
dsInferError("Could not find Custom Engine Creation Function '%s' in custom lib",
initParams.customEngineCreateFuncName);
return nullptr;
}
}
if (m_DlLib && cudaEngineGetFcn == nullptr)
cudaEngineGetDeprecatedFcn = m_DlLib->symbol<NvDsInferCudaEngineGetFcnDeprecated>(
"NvDsInferCudaEngineGet");
if (cudaEngineGetFcn || cudaEngineGetDeprecatedFcn ||
!string_empty(initParams.tltEncodedModelFilePath))
{
if (cudaEngineGetFcn || cudaEngineGetDeprecatedFcn)
{
/* NvDsInferCudaEngineGet interface provided. */
char *cwd = getcwd(NULL, 0);
modelPath = std::string(cwd) + "/model";
free(cwd);
}
else
{
/* TLT model. Use NvDsInferCudaEngineGetFromTltModel function
* provided by nvdsinferutils. */
cudaEngineGetFcn = NvDsInferCudaEngineGetFromTltModel;
modelPath = safeStr(initParams.tltEncodedModelFilePath);
}
engine = getCudaEngineFromCustomLib (cudaEngineGetDeprecatedFcn,
cudaEngineGetFcn, initParams, networkMode);
if (engine == nullptr)
{
dsInferError("Failed to get cuda engine from custom library API");
return nullptr;
}
}
else
{
/* Parse the network. */
NvDsInferStatus status = buildNetwork(initParams);
if (status != NVDSINFER_SUCCESS)
{
dsInferError("failed to build network.");
return nullptr;
}
assert(m_Parser);
assert(m_Network);
assert(m_Options);
/* Build the engine from the parsed network and build parameters. */
engine = buildEngine();
if (engine == nullptr)
{
dsInferError("failed to build trt engine.");
return nullptr;
}
modelPath = safeStr(m_Parser->getModelName());
networkMode = m_Options->networkMode;
}
std::string devId = std::string("gpu") + std::to_string(m_GpuId);
if (initParams.useDLA && initParams.dlaCore >= 0)
{
devId = std::string("dla") + std::to_string(initParams.dlaCore);
}
/* Construct the suggested path for engine file. */
suggestedPathName =
modelPath + "_b" + std::to_string(initParams.maxBatchSize) + "_" +
devId + "_" + networkMode2Str(networkMode) + ".engine";
return engine;
}
NvDsInferStatus
TrtModelBuilder::buildNetwork(const NvDsInferContextInitParams& initParams)
{
std::unique_ptr<BaseModelParser> parser;
assert(m_Builder);
/* check custom model parser first */
if (m_DlLib && READ_SYMBOL(m_DlLib, NvDsInferCreateModelParser))
{
parser.reset(new CustomModelParser(initParams, m_DlLib));
}
/* Check for caffe model files. */
else if (!string_empty(initParams.modelFilePath) &&
!string_empty(initParams.protoFilePath))
{
parser.reset(new CaffeModelParser(initParams, m_DlLib));
}
/* Check for UFF model. */
else if (!string_empty(initParams.uffFilePath))
{
parser.reset(new UffModelParser(initParams, m_DlLib));
}
/* Check for Onnx model. */
else if (!string_empty(initParams.onnxFilePath))
{
parser.reset(new OnnxModelParser(initParams, m_DlLib));
}
else
{
dsInferError(
"failed to build network since there is no model file matched.");
return NVDSINFER_CONFIG_FAILED;
}
if (!parser || !parser->isValid())
{
dsInferError("failed to build network because of invalid parsers.");
return NVDSINFER_CONFIG_FAILED;
}
std::unique_ptr<BuildParams> buildOptions;
nvinfer1::NetworkDefinitionCreationFlags netDefFlags = 0;
/* Create build parameters to build the network as a full dimension network
* only if the parser supports it and DLA is not to be used. Otherwise build
* the network as an implicit batch dim network. */
if (parser->hasFullDimsSupported() &&
!initParams.forceImplicitBatchDimension)
{
netDefFlags |=
(1U << static_cast<uint32_t>(
nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH));
buildOptions = createDynamicParams(initParams);
}
else
{
buildOptions = createImplicitParams(initParams);
}
const auto explicitBatch = 1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
UniquePtrWDestroy<nvinfer1::INetworkDefinition> network = m_Builder->createNetworkV2(explicitBatch);
assert(network);
/* Parse the model using IModelParser interface. */
NvDsInferStatus status = parser->parseModel(*network);
if (status != NVDSINFER_SUCCESS)
{
dsInferError("failed to build network since parsing model errors.");
return status;
}
assert(!m_Network);
m_Network = std::move(network);
m_Options = std::move(buildOptions);
m_Parser = std::move(parser);
return NVDSINFER_SUCCESS;
}
/* Create build parameters for implicit batch dim network. */
std::unique_ptr<BuildParams>
TrtModelBuilder::createImplicitParams(const NvDsInferContextInitParams& initParams)
{
auto params = std::make_unique<ImplicitBuildParams>();
if (initParams.uffDimsCHW.c && initParams.uffDimsCHW.h &&
initParams.uffDimsCHW.w)
{
params->inputDims.emplace_back(ds2TrtDims(initParams.uffDimsCHW));
}
else if (initParams.inferInputDims.c && initParams.inferInputDims.h &&
initParams.inferInputDims.w)
{
params->inputDims.emplace_back(ds2TrtDims(initParams.inferInputDims));
}
params->maxBatchSize = initParams.maxBatchSize;
initCommonParams(*params, initParams);