forked from Smorodov/Multitarget-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsampleEngines.cpp
More file actions
1629 lines (1473 loc) · 64.5 KB
/
sampleEngines.cpp
File metadata and controls
1629 lines (1473 loc) · 64.5 KB
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) 1993-2022, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <random>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "NvInfer.h"
#include "NvOnnxParser.h"
#include "common.h"
#include "ErrorRecorder.h"
#include "half.h"
#include "logger.h"
#include "sampleEngines.h"
#include "sampleOptions.h"
#include "sampleUtils.h"
#if !defined(_WIN32)
#include <dlfcn.h>
#endif
namespace sample
{
namespace
{
std::map<std::string, float> readScalesFromCalibrationCache(const std::string& calibrationFile)
{
std::map<std::string, float> tensorScales;
std::ifstream cache{calibrationFile};
if (!cache.is_open())
{
sample::gLogError << "[TRT] Can not open provided calibration cache file" << std::endl;
return tensorScales;
}
std::string line;
while (std::getline(cache, line))
{
auto colonPos = line.find_last_of(':');
if (colonPos != std::string::npos)
{
// Scales should be stored in calibration cache as 32-bit floating numbers encoded as 32-bit integers
int32_t scalesAsInt = std::stoi(line.substr(colonPos + 2, 8), nullptr, 16);
const auto tensorName = line.substr(0, colonPos);
tensorScales[tensorName] = *reinterpret_cast<float*>(&scalesAsInt);
}
}
cache.close();
return tensorScales;
}
} // namespace
void setTensorScalesFromCalibration(nvinfer1::INetworkDefinition& network, const std::vector<IOFormat>& inputFormats,
const std::vector<IOFormat>& outputFormats, const std::string& calibrationFile)
{
const auto tensorScales = readScalesFromCalibrationCache(calibrationFile);
const bool broadcastInputFormats = broadcastIOFormats(inputFormats, network.getNbInputs());
for (int32_t i = 0, n = network.getNbInputs(); i < n; ++i)
{
int32_t formatIdx = broadcastInputFormats ? 0 : i;
if (!inputFormats.empty() && inputFormats[formatIdx].first == nvinfer1::DataType::kINT8)
{
auto* input = network.getInput(i);
const auto calibScale = tensorScales.at(input->getName());
input->setDynamicRange(-127 * calibScale, 127 * calibScale);
}
}
const bool broadcastOutputFormats = broadcastIOFormats(outputFormats, network.getNbInputs());
for (int32_t i = 0, n = network.getNbOutputs(); i < n; ++i)
{
int32_t formatIdx = broadcastOutputFormats ? 0 : i;
if (!outputFormats.empty() && outputFormats[formatIdx].first == nvinfer1::DataType::kINT8)
{
auto* output = network.getOutput(i);
const auto calibScale = tensorScales.at(output->getName());
output->setDynamicRange(-127 * calibScale, 127 * calibScale);
}
}
}
#define SMP_RETVAL_IF_FALSE(condition, msg, retval, err) \
{ \
if ((condition) == false) \
{ \
(err) << (msg) << std::endl; \
return retval; \
} \
}
Parser modelToNetwork(const ModelOptions& model, nvinfer1::INetworkDefinition& network, std::ostream& err)
{
sample::gLogInfo << "Start parsing network model" << std::endl;
Parser parser;
//const std::string& modelName = model.baseModel.model;
switch (model.baseModel.format)
{
case ModelFormat::kONNX:
{
using namespace nvonnxparser;
parser.onnxParser.reset(createParser(network, sample::gLogger.getTRTLogger()));
if (!parser.onnxParser->parseFromFile(
model.baseModel.model.c_str(), static_cast<int>(sample::gLogger.getReportableSeverity())))
{
err << "Failed to parse onnx file" << std::endl;
parser.onnxParser.reset();
}
break;
}
case ModelFormat::kANY:
break;
default:
break;
}
sample::gLogInfo << "Finish parsing network model" << std::endl;
return parser;
}
namespace
{
class RndInt8Calibrator : public nvinfer1::IInt8EntropyCalibrator2
{
public:
RndInt8Calibrator(int batches, std::vector<int64_t>& elemCount, const std::string& cacheFile,
const nvinfer1::INetworkDefinition& network, std::ostream& err);
~RndInt8Calibrator()
{
for (auto& elem : mInputDeviceBuffers)
{
cudaCheck(cudaFree(elem.second), mErr);
}
}
bool getBatch(void* bindings[], const char* names[], int nbBindings) noexcept override;
int getBatchSize() const noexcept override
{
return 1;
}
const void* readCalibrationCache(size_t& length) noexcept override;
virtual void writeCalibrationCache(const void*, size_t) noexcept override {}
private:
int mBatches{};
int mCurrentBatch{};
std::string mCacheFile;
std::map<std::string, void*> mInputDeviceBuffers;
std::vector<char> mCalibrationCache;
std::ostream& mErr;
};
RndInt8Calibrator::RndInt8Calibrator(int batches, std::vector<int64_t>& elemCount, const std::string& cacheFile,
const nvinfer1::INetworkDefinition& network, std::ostream& err)
: mBatches(batches)
, mCurrentBatch(0)
, mCacheFile(cacheFile)
, mErr(err)
{
std::ifstream tryCache(cacheFile, std::ios::binary);
if (tryCache.good())
{
return;
}
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(-1.0F, 1.0F);
auto gen = [&generator, &distribution]() { return distribution(generator); };
for (int i = 0; i < network.getNbInputs(); i++)
{
auto* input = network.getInput(i);
std::vector<float> rnd_data(elemCount[i]);
std::generate_n(rnd_data.begin(), elemCount[i], gen);
void* data;
cudaCheck(cudaMalloc(&data, elemCount[i] * sizeof(float)), mErr);
cudaCheck(cudaMemcpy(data, rnd_data.data(), elemCount[i] * sizeof(float), cudaMemcpyHostToDevice), mErr);
mInputDeviceBuffers.insert(std::make_pair(input->getName(), data));
}
}
bool RndInt8Calibrator::getBatch(void* bindings[], const char* names[], int nbBindings) noexcept
{
if (mCurrentBatch >= mBatches)
{
return false;
}
for (int i = 0; i < nbBindings; ++i)
{
bindings[i] = mInputDeviceBuffers[names[i]];
}
++mCurrentBatch;
return true;
}
const void* RndInt8Calibrator::readCalibrationCache(size_t& length) noexcept
{
mCalibrationCache.clear();
std::ifstream input(mCacheFile, std::ios::binary);
input >> std::noskipws;
if (input.good())
{
std::copy(
std::istream_iterator<char>(input), std::istream_iterator<char>(), std::back_inserter(mCalibrationCache));
}
length = mCalibrationCache.size();
return !mCalibrationCache.empty() ? mCalibrationCache.data() : nullptr;
}
bool setTensorDynamicRange(const nvinfer1::INetworkDefinition& network, float inRange = 2.0F, float outRange = 4.0F)
{
// Ensure that all layer inputs have a dynamic range.
for (int l = 0; l < network.getNbLayers(); l++)
{
auto* layer = network.getLayer(l);
for (int i = 0; i < layer->getNbInputs(); i++)
{
nvinfer1::ITensor* input{layer->getInput(i)};
// Optional inputs are nullptr here and are from RNN layers.
if (input && !input->dynamicRangeIsSet())
{
// Concat should propagate dynamic range from outputs to inputs to avoid
// Re-quantization during the concatenation
auto dynRange = (layer->getType() == nvinfer1::LayerType::kCONCATENATION) ? outRange : inRange;
if (!input->setDynamicRange(-dynRange, dynRange))
{
return false;
}
}
}
for (int o = 0; o < layer->getNbOutputs(); o++)
{
nvinfer1::ITensor* output{layer->getOutput(o)};
// Optional outputs are nullptr here and are from RNN layers.
if (output && !output->dynamicRangeIsSet())
{
// Pooling must have the same input and output dynamic range.
if (layer->getType() == nvinfer1::LayerType::kPOOLING)
{
if (!output->setDynamicRange(-inRange, inRange))
{
return false;
}
}
else
{
if (!output->setDynamicRange(-outRange, outRange))
{
return false;
}
}
}
}
}
return true;
}
// Walk the weights elements and overwrite (at most) 2 out of 4 elements to 0.
template <typename T>
void sparsify(const T* values, int64_t count, int32_t k, int32_t rs, std::vector<char>& sparseWeights)
{
const auto c = count / (k * rs);
sparseWeights.resize(count * sizeof(T));
auto* sparseValues = reinterpret_cast<T*>(sparseWeights.data());
constexpr int32_t window = 4;
constexpr int32_t nonzeros = 2;
const int32_t crs = c * rs;
const auto getIndex = [=](int32_t ki, int32_t ci, int32_t rsi) { return ki * crs + ci * rs + rsi; };
for (int64_t ki = 0; ki < k; ++ki)
{
for (int64_t rsi = 0; rsi < rs; ++rsi)
{
int32_t w = 0;
int32_t nz = 0;
for (int64_t ci = 0; ci < c; ++ci)
{
const auto index = getIndex(ki, ci, rsi);
if (nz < nonzeros)
{
sparseValues[index] = values[index];
++nz;
}
else
{
sparseValues[index] = 0;
}
if (++w == window)
{
w = 0;
nz = 0;
}
}
}
}
}
void sparsify(const nvinfer1::Weights& weights, int32_t k, int32_t rs, std::vector<char>& sparseWeights)
{
switch (weights.type)
{
case nvinfer1::DataType::kFLOAT:
sparsify(static_cast<const float*>(weights.values), weights.count, k, rs, sparseWeights);
break;
case nvinfer1::DataType::kHALF:
sparsify(static_cast<const half_float::half*>(weights.values), weights.count, k, rs, sparseWeights);
break;
case nvinfer1::DataType::kINT8:
case nvinfer1::DataType::kINT32:
case nvinfer1::DataType::kBOOL: break;
}
}
template <typename L>
void setSparseWeights(L& l, int32_t k, int32_t rs, std::vector<char>& sparseWeights)
{
auto weights = l.getKernelWeights();
sparsify(weights, k, rs, sparseWeights);
weights.values = sparseWeights.data();
l.setKernelWeights(weights);
}
template <typename T>
void transpose2DWeights(void* dst, void const* src, int32_t const m, int32_t const n)
{
ASSERT(dst != src);
T* tdst = reinterpret_cast<T*>(dst);
T const* tsrc = reinterpret_cast<T const*>(src);
for (int32_t mi = 0; mi < m; ++mi)
{
for (int32_t ni = 0; ni < n; ++ni)
{
int32_t const isrc = mi * n + ni;
int32_t const idst = ni * m + mi;
tdst[idst] = tsrc[isrc];
}
}
}
// Sparsify the weights of Constant layers that are fed to MatMul via Shuffle layers.
// Forward analysis on the API graph to determine which weights to sparsify.
void sparsifyMatMulKernelWeights(nvinfer1::INetworkDefinition& network, std::vector<std::vector<char>>& sparseWeights)
{
using TensorToLayer = std::unordered_map<nvinfer1::ITensor*, nvinfer1::ILayer*>;
using LayerToTensor = std::unordered_map<nvinfer1::ILayer*, nvinfer1::ITensor*>;
// 1. Collect layers and tensors information from the network.
TensorToLayer matmulI2L;
TensorToLayer constO2L;
TensorToLayer shuffleI2L;
LayerToTensor shuffleL2O;
auto collectMappingInfo = [&](int32_t const idx) {
nvinfer1::ILayer* l = network.getLayer(idx);
switch (l->getType())
{
case nvinfer1::LayerType::kMATRIX_MULTIPLY:
{
// assume weights on the second input.
matmulI2L.insert({l->getInput(1), l});
break;
}
case nvinfer1::LayerType::kCONSTANT:
{
nvinfer1::DataType const dtype = static_cast<nvinfer1::IConstantLayer*>(l)->getWeights().type;
if (dtype == nvinfer1::DataType::kFLOAT || dtype == nvinfer1::DataType::kHALF)
{
// Sparsify float only.
constO2L.insert({l->getOutput(0), l});
}
break;
}
case nvinfer1::LayerType::kSHUFFLE:
{
shuffleI2L.insert({l->getInput(0), l});
shuffleL2O.insert({l, l->getOutput(0)});
break;
}
default: break;
}
};
int32_t const nbLayers = network.getNbLayers();
for (int32_t i = 0; i < nbLayers; ++i)
{
collectMappingInfo(i);
}
if (matmulI2L.size() == 0 || constO2L.size() == 0)
{
// No MatrixMultiply or Constant layer found, no weights to sparsify.
return;
}
// Helper for analysis
auto isTranspose = [](nvinfer1::Permutation const& perm) -> bool { return (perm.order[0] == 1 && perm.order[1] == 0); };
auto is2D = [](nvinfer1::Dims const& dims) -> bool { return dims.nbDims == 2; };
auto isIdenticalReshape = [](nvinfer1::Dims const& dims) -> bool {
for (int32_t i = 0; i < dims.nbDims; ++i)
{
if (dims.d[i] != i || dims.d[i] != -1)
{
return false;
}
}
return true;
};
auto tensorReachedViaTranspose = [&](nvinfer1::ITensor* t, bool& needTranspose)
{
while (shuffleI2L.find(t) != shuffleI2L.end())
{
nvinfer1::IShuffleLayer* s = static_cast<nvinfer1::IShuffleLayer*>(shuffleI2L.at(t));
if (!is2D(s->getInput(0)->getDimensions()) || !is2D(s->getReshapeDimensions())
|| !isIdenticalReshape(s->getReshapeDimensions()))
{
break;
}
if (isTranspose(s->getFirstTranspose()))
needTranspose = !needTranspose;
if (isTranspose(s->getSecondTranspose()))
needTranspose = !needTranspose;
t = shuffleL2O.at(s);
}
return t;
};
// 2. Forward analysis to collect the Constant layers connected to MatMul via Transpose
std::unordered_map<nvinfer1::IConstantLayer*, bool> constantLayerToSparse;
for (auto& o2l : constO2L)
{
// If need to transpose the weights of the Constant layer.
// Need to transpose by default due to semantic difference.
bool needTranspose{true};
nvinfer1::ITensor* t = tensorReachedViaTranspose(o2l.first, needTranspose);
if (matmulI2L.find(t) == matmulI2L.end())
{
continue;
}
// check MatMul params...
nvinfer1::IMatrixMultiplyLayer* mm = static_cast<nvinfer1::IMatrixMultiplyLayer*>(matmulI2L.at(t));
bool const twoInputs = mm->getNbInputs() == 2;
bool const all2D = is2D(mm->getInput(0)->getDimensions()) && is2D(mm->getInput(1)->getDimensions());
bool const isSimple
= mm->getOperation(0) == nvinfer1::MatrixOperation::kNONE && mm->getOperation(1) != nvinfer1::MatrixOperation::kVECTOR;
if (!(twoInputs && all2D && isSimple))
continue;
if (mm->getOperation(1) == nvinfer1::MatrixOperation::kTRANSPOSE)
needTranspose = !needTranspose;
constantLayerToSparse.insert({static_cast<nvinfer1::IConstantLayer*>(o2l.second), needTranspose});
}
// 3. Finally, sparsify the weights
auto sparsifyConstantWeights = [&sparseWeights](nvinfer1::IConstantLayer* layer, bool const needTranspose)
{
nvinfer1::Dims dims = layer->getOutput(0)->getDimensions();
ASSERT(dims.nbDims == 2);
int32_t const idxN = needTranspose ? 1 : 0;
int32_t const n = dims.d[idxN];
int32_t const k = dims.d[1 - idxN];
sparseWeights.emplace_back();
std::vector<char>& spw = sparseWeights.back();
nvinfer1::Weights w = layer->getWeights();
nvinfer1::DataType const dtype = w.type;
ASSERT(dtype == nvinfer1::DataType::kFLOAT || dtype == nvinfer1::DataType::kHALF); // non-float weights should have been ignored.
if (needTranspose)
{
if (dtype == nvinfer1::DataType::kFLOAT)
{
spw.resize(w.count * sizeof(float));
transpose2DWeights<float>(spw.data(), w.values, k, n);
}
else if (dtype == nvinfer1::DataType::kHALF)
{
spw.resize(w.count * sizeof(half_float::half));
transpose2DWeights<half_float::half>(spw.data(), w.values, k, n);
}
w.values = spw.data();
std::vector<char> tmpW;
sparsify(w, n, 1, tmpW);
if (dtype == nvinfer1::DataType::kFLOAT)
transpose2DWeights<float>(spw.data(), tmpW.data(), n, k);
else if (dtype == nvinfer1::DataType::kHALF)
transpose2DWeights<half_float::half>(spw.data(), tmpW.data(), n, k);
}
else
{
sparsify(w, n, 1, spw);
}
w.values = spw.data();
layer->setWeights(w);
};
for (auto& l : constantLayerToSparse)
{
sparsifyConstantWeights(l.first, l.second);
}
}
void sparsify(nvinfer1::INetworkDefinition& network, std::vector<std::vector<char>>& sparseWeights)
{
for (int32_t l = 0; l < network.getNbLayers(); ++l)
{
auto* layer = network.getLayer(l);
const auto t = layer->getType();
if (t == nvinfer1::LayerType::kCONVOLUTION)
{
auto& conv = *static_cast<nvinfer1::IConvolutionLayer*>(layer);
const auto& dims = conv.getKernelSizeNd();
if (dims.nbDims > 2)
{
continue;
}
const auto k = conv.getNbOutputMaps();
const auto rs = dims.d[0] * dims.d[1];
sparseWeights.emplace_back();
setSparseWeights(conv, k, rs, sparseWeights.back());
}
else if (t == nvinfer1::LayerType::kFULLY_CONNECTED)
{
auto& fc = *static_cast<nvinfer1::IFullyConnectedLayer*>(layer);
const auto k = fc.getNbOutputChannels();
sparseWeights.emplace_back();
setSparseWeights(fc, k, 1, sparseWeights.back());
}
}
sparsifyMatMulKernelWeights(network, sparseWeights);
}
void setLayerPrecisions(nvinfer1::INetworkDefinition& network, LayerPrecisions const& layerPrecisions)
{
bool const hasGlobalPrecision{layerPrecisions.find("*") != layerPrecisions.end()};
auto const globalPrecision = hasGlobalPrecision ? layerPrecisions.at("*") : nvinfer1::DataType::kFLOAT;
bool hasLayerPrecisionSkipped{false};
for (int32_t layerIdx = 0; layerIdx < network.getNbLayers(); ++layerIdx)
{
auto* layer = network.getLayer(layerIdx);
auto const layerName = layer->getName();
if (layerPrecisions.find(layer->getName()) != layerPrecisions.end())
{
layer->setPrecision(layerPrecisions.at(layer->getName()));
}
else if (hasGlobalPrecision)
{
// We should not set the layer precision if its default precision is INT32 or Bool.
if (layer->getPrecision() == nvinfer1::DataType::kINT32
|| layer->getPrecision() == nvinfer1::DataType::kBOOL)
{
hasLayerPrecisionSkipped = true;
sample::gLogVerbose << "Skipped setting precision for layer " << layerName << " because the "
<< " default layer precision is INT32 or Bool." << std::endl;
continue;
}
// We should not set the constant layer precision if its weights are in INT32.
if (layer->getType() == nvinfer1::LayerType::kCONSTANT
&& static_cast<nvinfer1::IConstantLayer*>(layer)->getWeights().type == nvinfer1::DataType::kINT32)
{
hasLayerPrecisionSkipped = true;
sample::gLogVerbose << "Skipped setting precision for layer " << layerName << " because this "
<< "constant layer has INT32 weights." << std::endl;
continue;
}
// We should not set the layer precision if the layer operates on a shape tensor.
if (layer->getNbInputs() >= 1 && layer->getInput(0)->isShapeTensor())
{
hasLayerPrecisionSkipped = true;
sample::gLogVerbose << "Skipped setting precision for layer " << layerName << " because this layer "
<< "operates on a shape tensor." << std::endl;
continue;
}
if ((layer->getType() == nvinfer1::LayerType::kIDENTITY
|| layer->getType() == nvinfer1::LayerType::kSHUFFLE)
&& layer->getNbInputs() >= 1 && layer->getInput(0)->getType() == nvinfer1::DataType::kINT32
&& layer->getNbOutputs() >= 1 && layer->getOutput(0)->getType() == nvinfer1::DataType::kINT32)
{
hasLayerPrecisionSkipped = true;
sample::gLogVerbose << "Skipped setting precision for layer " << layerName << " because this "
<< "layer has INT32 input and output." << std::endl;
continue;
}
// All heuristics passed. Set the layer precision.
layer->setPrecision(globalPrecision);
}
}
if (hasLayerPrecisionSkipped)
{
sample::gLogInfo << "Skipped setting precisions for some layers. Check verbose logs for more details."
<< std::endl;
}
}
void setLayerOutputTypes(nvinfer1::INetworkDefinition& network, LayerOutputTypes const& layerOutputTypes)
{
bool const hasGlobalOutputType{layerOutputTypes.find("*") != layerOutputTypes.end()};
auto const globalOutputType = hasGlobalOutputType ? layerOutputTypes.at("*").at(0) : nvinfer1::DataType::kFLOAT;
bool hasLayerOutputTypeSkipped{false};
for (int32_t layerIdx = 0; layerIdx < network.getNbLayers(); ++layerIdx)
{
auto* layer = network.getLayer(layerIdx);
auto const layerName = layer->getName();
auto const nbOutputs = layer->getNbOutputs();
if (layerOutputTypes.find(layer->getName()) != layerOutputTypes.end())
{
auto const& outputTypes = layerOutputTypes.at(layer->getName());
bool const isBroadcast = (outputTypes.size() == 1);
if (!isBroadcast && static_cast<int32_t>(outputTypes.size()) != nbOutputs)
{
sample::gLogError << "Layer " << layerName << " has " << nbOutputs << " outputs but "
<< outputTypes.size() << " output types are given in --layerOutputTypes flag."
<< std::endl;
throw std::invalid_argument("Invalid --layerOutputTypes flag.");
}
for (int32_t outputIdx = 0; outputIdx < nbOutputs; ++outputIdx)
{
layer->setOutputType(outputIdx, outputTypes.at(isBroadcast ? 0 : outputIdx));
}
}
else if (hasGlobalOutputType)
{
// We should not set the layer output types if its default precision is INT32 or Bool.
if (layer->getPrecision() == nvinfer1::DataType::kINT32
|| layer->getPrecision() == nvinfer1::DataType::kBOOL)
{
hasLayerOutputTypeSkipped = true;
sample::gLogVerbose << "Skipped setting output types for layer " << layerName << " because the "
<< " default layer precision is INT32 or Bool." << std::endl;
continue;
}
// We should not set the constant layer output types if its weights are in INT32.
if (layer->getType() == nvinfer1::LayerType::kCONSTANT
&& static_cast<nvinfer1::IConstantLayer*>(layer)->getWeights().type == nvinfer1::DataType::kINT32)
{
hasLayerOutputTypeSkipped = true;
sample::gLogVerbose << "Skipped setting output types for layer " << layerName << " because this "
<< "constant layer has INT32 weights." << std::endl;
continue;
}
for (int32_t outputIdx = 0; outputIdx < nbOutputs; ++outputIdx)
{
// We should not set the output type if the output is a shape tensor.
if (layer->getOutput(0)->isShapeTensor())
{
hasLayerOutputTypeSkipped = true;
sample::gLogVerbose << "Skipped setting output type for output " << outputIdx << " of layer "
<< layerName << " because it is a shape tensor." << std::endl;
continue;
}
layer->setOutputType(outputIdx, globalOutputType);
}
}
}
if (hasLayerOutputTypeSkipped)
{
sample::gLogInfo << "Skipped setting output types for some layers. Check verbose logs for more details."
<< std::endl;
}
}
void setMemoryPoolLimits(nvinfer1::IBuilderConfig& config, BuildOptions const& build)
{
auto const roundToBytes = [](double const sizeInMB) { return static_cast<size_t>(sizeInMB * (1 << 20)); };
if (build.workspace >= 0)
config.setMemoryPoolLimit(nvinfer1::MemoryPoolType::kWORKSPACE, roundToBytes(build.workspace));
if (build.dlaSRAM >= 0)
config.setMemoryPoolLimit(nvinfer1::MemoryPoolType::kDLA_MANAGED_SRAM, roundToBytes(build.dlaSRAM));
if (build.dlaLocalDRAM >= 0)
config.setMemoryPoolLimit(nvinfer1::MemoryPoolType::kDLA_LOCAL_DRAM, roundToBytes(build.dlaLocalDRAM));
if (build.dlaGlobalDRAM >= 0)
config.setMemoryPoolLimit(nvinfer1::MemoryPoolType::kDLA_GLOBAL_DRAM, roundToBytes(build.dlaGlobalDRAM));
}
} // namespace
bool setupNetworkAndConfig(const BuildOptions& build, const SystemOptions& sys, nvinfer1::IBuilder& builder,
nvinfer1::INetworkDefinition& network, nvinfer1::IBuilderConfig& config, std::ostream& err,
std::vector<std::vector<char>>& sparseWeights)
{
nvinfer1::IOptimizationProfile* profile{nullptr};
if (build.maxBatch)
builder.setMaxBatchSize(build.maxBatch);
else
profile = builder.createOptimizationProfile();
bool hasDynamicShapes{false};
bool broadcastInputFormats = broadcastIOFormats(build.inputFormats, network.getNbInputs());
if (profile)
{
// Check if the provided input tensor names match the input tensors of the engine.
// Throw an error if the provided input tensor names cannot be found because it implies a potential typo.
for (const auto& shape : build.shapes)
{
bool tensorNameFound{false};
for (int32_t i = 0; i < network.getNbInputs(); ++i)
{
if (network.getInput(i)->getName() == shape.first)
{
tensorNameFound = true;
break;
}
}
if (!tensorNameFound)
{
sample::gLogError << "Cannot find input tensor with name \"" << shape.first << "\" in the network "
<< "inputs! Please make sure the input tensor names are correct." << std::endl;
return false;
}
}
}
for (uint32_t i = 0, n = network.getNbInputs(); i < n; i++)
{
// Set formats and data types of inputs
auto* input = network.getInput(i);
if (!build.inputFormats.empty())
{
int inputFormatIndex = broadcastInputFormats ? 0 : i;
input->setType(build.inputFormats[inputFormatIndex].first);
input->setAllowedFormats(build.inputFormats[inputFormatIndex].second);
}
else
{
switch (input->getType())
{
case nvinfer1::DataType::kINT32:
case nvinfer1::DataType::kBOOL:
case nvinfer1::DataType::kHALF:
// Leave these as is.
break;
case nvinfer1::DataType::kFLOAT:
case nvinfer1::DataType::kINT8:
// User did not specify a floating-point format. Default to kFLOAT.
input->setType(nvinfer1::DataType::kFLOAT);
break;
}
input->setAllowedFormats(1U << static_cast<int>(nvinfer1::TensorFormat::kLINEAR));
}
if (profile)
{
auto const dims = input->getDimensions();
auto const isScalar = dims.nbDims == 0;
auto const isDynamicInput = std::any_of(dims.d, dims.d + dims.nbDims, [](int32_t dim) { return dim == -1; })
|| input->isShapeTensor();
if (isDynamicInput)
{
hasDynamicShapes = true;
auto shape = build.shapes.find(input->getName());
ShapeRange shapes{};
// If no shape is provided, set dynamic dimensions to 1.
if (shape == build.shapes.end())
{
constexpr int DEFAULT_DIMENSION = 1;
std::vector<int> staticDims;
if (input->isShapeTensor())
{
if (isScalar)
{
staticDims.push_back(1);
}
else
{
staticDims.resize(dims.d[0]);
std::fill(staticDims.begin(), staticDims.end(), DEFAULT_DIMENSION);
}
}
else
{
staticDims.resize(dims.nbDims);
std::transform(dims.d, dims.d + dims.nbDims, staticDims.begin(),
[&](int dimension) { return dimension > 0 ? dimension : DEFAULT_DIMENSION; });
}
sample::gLogWarning << "Dynamic dimensions required for input: " << input->getName()
<< ", but no shapes were provided. Automatically overriding shape to: "
<< staticDims << std::endl;
std::fill(shapes.begin(), shapes.end(), staticDims);
}
else
{
shapes = shape->second;
}
std::vector<int> profileDims{};
if (input->isShapeTensor())
{
profileDims = shapes[static_cast<size_t>(nvinfer1::OptProfileSelector::kMIN)];
SMP_RETVAL_IF_FALSE(profile->setShapeValues(input->getName(), nvinfer1::OptProfileSelector::kMIN,
profileDims.data(), static_cast<int>(profileDims.size())),
"Error in set shape values MIN", false, err);
profileDims = shapes[static_cast<size_t>(nvinfer1::OptProfileSelector::kOPT)];
SMP_RETVAL_IF_FALSE(profile->setShapeValues(input->getName(), nvinfer1::OptProfileSelector::kOPT,
profileDims.data(), static_cast<int>(profileDims.size())),
"Error in set shape values OPT", false, err);
profileDims = shapes[static_cast<size_t>(nvinfer1::OptProfileSelector::kMAX)];
SMP_RETVAL_IF_FALSE(profile->setShapeValues(input->getName(), nvinfer1::OptProfileSelector::kMAX,
profileDims.data(), static_cast<int>(profileDims.size())),
"Error in set shape values MAX", false, err);
}
else
{
profileDims = shapes[static_cast<size_t>(nvinfer1::OptProfileSelector::kMIN)];
SMP_RETVAL_IF_FALSE(
profile->setDimensions(input->getName(), nvinfer1::OptProfileSelector::kMIN, toDims(profileDims)),
"Error in set dimensions to profile MIN", false, err);
profileDims = shapes[static_cast<size_t>(nvinfer1::OptProfileSelector::kOPT)];
SMP_RETVAL_IF_FALSE(
profile->setDimensions(input->getName(), nvinfer1::OptProfileSelector::kOPT, toDims(profileDims)),
"Error in set dimensions to profile OPT", false, err);
profileDims = shapes[static_cast<size_t>(nvinfer1::OptProfileSelector::kMAX)];
SMP_RETVAL_IF_FALSE(
profile->setDimensions(input->getName(), nvinfer1::OptProfileSelector::kMAX, toDims(profileDims)),
"Error in set dimensions to profile MAX", false, err);
}
}
}
}
if (!hasDynamicShapes && !build.shapes.empty())
{
sample::gLogError << "Static model does not take explicit shapes since the shape of inference tensors will be "
"determined by the model itself"
<< std::endl;
return false;
}
if (profile && hasDynamicShapes)
{
SMP_RETVAL_IF_FALSE(profile->isValid(), "Required optimization profile is invalid", false, err);
SMP_RETVAL_IF_FALSE(config.addOptimizationProfile(profile) != -1, "Error in add optimization profile", false, err);
}
bool broadcastOutputFormats = broadcastIOFormats(build.outputFormats, network.getNbOutputs(), false);
for (uint32_t i = 0, n = network.getNbOutputs(); i < n; i++)
{
// Set formats and data types of outputs
auto* output = network.getOutput(i);
if (!build.outputFormats.empty())
{
int outputFormatIndex = broadcastOutputFormats ? 0 : i;
output->setType(build.outputFormats[outputFormatIndex].first);
output->setAllowedFormats(build.outputFormats[outputFormatIndex].second);
}
else
{
output->setAllowedFormats(1U << static_cast<int>(nvinfer1::TensorFormat::kLINEAR));
}
}
setMemoryPoolLimits(config, build);
if (build.timingCacheMode == TimingCacheMode::kDISABLE)
config.setFlag(nvinfer1::BuilderFlag::kDISABLE_TIMING_CACHE);
if (!build.tf32)
config.clearFlag(nvinfer1::BuilderFlag::kTF32);
if (build.refittable)
config.setFlag(nvinfer1::BuilderFlag::kREFIT);
if (build.sparsity != SparsityFlag::kDISABLE)
{
config.setFlag(nvinfer1::BuilderFlag::kSPARSE_WEIGHTS);
if (build.sparsity == SparsityFlag::kFORCE)
sparsify(network, sparseWeights);
}
config.setProfilingVerbosity(build.profilingVerbosity);
config.setMinTimingIterations(build.minTiming);
config.setAvgTimingIterations(build.avgTiming);
if (build.fp16)
config.setFlag(nvinfer1::BuilderFlag::kFP16);
if (build.int8)
config.setFlag(nvinfer1::BuilderFlag::kINT8);
if (build.int8 && !build.fp16)
{
sample::gLogInfo
<< "FP32 and INT8 precisions have been specified - more performance might be enabled by additionally "
"specifying --fp16 or --best"
<< std::endl;
}
auto isInt8 = [](const IOFormat& format) { return format.first == nvinfer1::DataType::kINT8; };
auto int8IO = std::count_if(build.inputFormats.begin(), build.inputFormats.end(), isInt8)
+ std::count_if(build.outputFormats.begin(), build.outputFormats.end(), isInt8);
auto hasQDQLayers = [](nvinfer1::INetworkDefinition& network) {
// Determine if our network has QDQ layers.
const auto nbLayers = network.getNbLayers();
for (int32_t i = 0; i < nbLayers; i++)
{
const auto& layer = network.getLayer(i);
if (layer->getType() == nvinfer1::LayerType::kQUANTIZE || layer->getType() == nvinfer1::LayerType::kDEQUANTIZE)
return true;
}
return false;
};
if (!hasQDQLayers(network) && (build.int8 || int8IO) && build.calibration.empty())
{
// Explicitly set int8 scales if no calibrator is provided and if I/O tensors use int8,
// because auto calibration does not support this case.
SMP_RETVAL_IF_FALSE(setTensorDynamicRange(network), "Error in set tensor dynamic range.", false, err);
}
else if (build.int8)
{
if (!hasQDQLayers(network) && int8IO)
{
try
{
// Set dynamic ranges of int8 inputs / outputs to match scales loaded from calibration cache
// TODO http://nvbugs/3262234 Change the network validation so that this workaround can be removed
setTensorScalesFromCalibration(network, build.inputFormats, build.outputFormats, build.calibration);
}
catch (std::exception&)
{
sample::gLogError
<< "Int8IO was specified but impossible to read tensor scales from provided calibration cache file"
<< std::endl;
return false;
}
}
nvinfer1::IOptimizationProfile* profileCalib{nullptr};
if (!build.shapesCalib.empty())
{
profileCalib = builder.createOptimizationProfile();
for (uint32_t i = 0, n = network.getNbInputs(); i < n; i++)
{
auto* input = network.getInput(i);
nvinfer1::Dims profileDims{};
auto shape = build.shapesCalib.find(input->getName());
ShapeRange shapesCalib{};
shapesCalib = shape->second;
profileDims = toDims(shapesCalib[static_cast<size_t>(nvinfer1::OptProfileSelector::kOPT)]);
// Here we check only kMIN as all profileDims are the same.
SMP_RETVAL_IF_FALSE(
profileCalib->setDimensions(input->getName(), nvinfer1::OptProfileSelector::kMIN, profileDims),
"Error in set dimensions to calibration profile OPT", false, err);
profileCalib->setDimensions(input->getName(), nvinfer1::OptProfileSelector::kOPT, profileDims);
profileCalib->setDimensions(input->getName(), nvinfer1::OptProfileSelector::kMAX, profileDims);
}
SMP_RETVAL_IF_FALSE(profileCalib->isValid(), "Calibration profile is invalid", false, err);
SMP_RETVAL_IF_FALSE(config.setCalibrationProfile(profileCalib), "Error in set calibration profile", false, err);
}
std::vector<int64_t> elemCount{};
for (int i = 0; i < network.getNbInputs(); i++)
{
auto* input = network.getInput(i);
auto const dims = input->getDimensions();
auto const isDynamicInput = std::any_of(dims.d, dims.d + dims.nbDims, [](int32_t dim) { return dim == -1; });
if (profileCalib)
elemCount.push_back(volume(profileCalib->getDimensions(input->getName(), nvinfer1::OptProfileSelector::kOPT)));