-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
sampleOptions.cpp
2694 lines (2472 loc) · 126 KB
/
sampleOptions.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
/*
* SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* 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 <cctype>
#include <cstring>
#include <functional>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include "NvInfer.h"
#include "logger.h"
#include "sampleOptions.h"
#include "sampleUtils.h"
using namespace nvinfer1;
namespace sample
{
namespace
{
static const std::map<char, std::pair<int64_t, std::string>> kUNIT_MULTIPLIERS{
{'B', {1, "Bytes"}},
{'K', {1 << 10, "Kibibytes"}},
{'M', {1 << 20, "Mebibytes"}},
{'G', {1 << 30, "Gibibytes"}},
};
// Returns "B (Bytes), K (Kilobytes), ..."
std::string getAvailableUnitSuffixes()
{
std::ostringstream ss;
for (auto it = kUNIT_MULTIPLIERS.begin(); it != kUNIT_MULTIPLIERS.end(); ++it)
{
if (it != kUNIT_MULTIPLIERS.begin())
{
ss << ", ";
}
ss << it->first << " (" << it->second.second << ")";
}
return ss.str();
}
// Numeric trtexec arguments can have unit specifiers in similar to polygraphy.
// E.g. --weightStreamingBudget=20M would be 20 Mebibytes (base 2).
int64_t getUnitMultiplier(std::string const& option)
{
char lastChar = option.at(option.size() - 1);
if (!std::isdigit(lastChar))
{
char unit = std::toupper(lastChar);
auto found = kUNIT_MULTIPLIERS.find(unit);
if (found == kUNIT_MULTIPLIERS.end())
{
std::ostringstream ss;
ss << "Error parsing \"" << option << "\": invalid unit specifier '" << unit
<< "'. Valid base-2 unit suffixes include: ";
ss << getAvailableUnitSuffixes() << ".";
throw std::invalid_argument(ss.str());
}
return found->second.first;
}
// Return bytes by default
return kUNIT_MULTIPLIERS.at('B').first;
}
template <typename T>
T stringToValue(const std::string& option)
{
return T{option};
}
template <>
int32_t stringToValue<int32_t>(const std::string& option)
{
return std::stoi(option);
}
template <>
size_t stringToValue<size_t>(const std::string& option)
{
return std::stoi(option) * getUnitMultiplier(option);
}
template <>
float stringToValue<float>(const std::string& option)
{
return std::stof(option);
}
template <>
double stringToValue<double>(const std::string& option)
{
return std::stod(option) * getUnitMultiplier(option);
}
template <>
bool stringToValue<bool>(const std::string& option)
{
return true;
}
template <>
std::vector<int32_t> stringToValue<std::vector<int32_t>>(const std::string& option)
{
std::vector<int32_t> shape;
if (option == "scalar")
{
return shape;
}
std::vector<std::string> dimsStrings = splitToStringVec(option, 'x');
for (const auto& d : dimsStrings)
{
shape.push_back(stringToValue<int32_t>(d));
}
return shape;
}
template <>
nvinfer1::DataType stringToValue<nvinfer1::DataType>(const std::string& option)
{
const std::unordered_map<std::string, nvinfer1::DataType> strToDT{{"fp32", nvinfer1::DataType::kFLOAT},
{"fp16", nvinfer1::DataType::kHALF}, {"bf16", nvinfer1::DataType::kBF16}, {"int8", nvinfer1::DataType::kINT8},
{"fp8", nvinfer1::DataType::kFP8}, {"int32", nvinfer1::DataType::kINT32}, {"int64", nvinfer1::DataType::kINT64},
{"bool", nvinfer1::DataType::kBOOL}, {"uint8", nvinfer1::DataType::kUINT8}};
const auto& dt = strToDT.find(option);
if (dt == strToDT.end())
{
throw std::invalid_argument("Invalid DataType " + option);
}
return dt->second;
}
template <>
nvinfer1::DeviceType stringToValue<nvinfer1::DeviceType>(std::string const& option)
{
std::unordered_map<std::string, nvinfer1::DeviceType> const strToDevice = {
{"GPU", nvinfer1::DeviceType::kGPU},
{"DLA", nvinfer1::DeviceType::kDLA},
};
auto const& device = strToDevice.find(option);
if (device == strToDevice.end())
{
throw std::invalid_argument("Invalid Device Type " + option);
}
return device->second;
}
template <>
nvinfer1::TensorFormats stringToValue<nvinfer1::TensorFormats>(const std::string& option)
{
std::vector<std::string> optionStrings = splitToStringVec(option, '+');
const std::unordered_map<std::string, nvinfer1::TensorFormat> strToFmt{{"chw", nvinfer1::TensorFormat::kLINEAR},
{"chw2", nvinfer1::TensorFormat::kCHW2}, {"chw4", nvinfer1::TensorFormat::kCHW4},
{"hwc8", nvinfer1::TensorFormat::kHWC8}, {"chw16", nvinfer1::TensorFormat::kCHW16},
{"chw32", nvinfer1::TensorFormat::kCHW32}, {"dhwc8", nvinfer1::TensorFormat::kDHWC8},
{"cdhw32", nvinfer1::TensorFormat::kCDHW32}, {"hwc", nvinfer1::TensorFormat::kHWC},
{"dhwc", nvinfer1::TensorFormat::kDHWC}, {"dla_linear", nvinfer1::TensorFormat::kDLA_LINEAR},
{"dla_hwc4", nvinfer1::TensorFormat::kDLA_HWC4}};
nvinfer1::TensorFormats formats{};
for (auto f : optionStrings)
{
const auto& tf = strToFmt.find(f);
if (tf == strToFmt.end())
{
throw std::invalid_argument(std::string("Invalid TensorFormat ") + f);
}
formats |= 1U << static_cast<int32_t>(tf->second);
}
return formats;
}
template <>
IOFormat stringToValue<IOFormat>(const std::string& option)
{
IOFormat ioFormat{};
const size_t colon = option.find(':');
if (colon == std::string::npos)
{
throw std::invalid_argument(std::string("Invalid IOFormat ") + option);
}
ioFormat.first = stringToValue<nvinfer1::DataType>(option.substr(0, colon));
ioFormat.second = stringToValue<nvinfer1::TensorFormats>(option.substr(colon + 1));
return ioFormat;
}
template <>
SparsityFlag stringToValue<SparsityFlag>(std::string const& option)
{
std::unordered_map<std::string, SparsityFlag> const table{
{"disable", SparsityFlag::kDISABLE}, {"enable", SparsityFlag::kENABLE}, {"force", SparsityFlag::kFORCE}};
auto search = table.find(option);
if (search == table.end())
{
throw std::invalid_argument(std::string("Unknown sparsity mode: ") + option);
}
if (search->second == SparsityFlag::kFORCE)
{
sample::gLogWarning << "--sparsity=force has been deprecated. "
<< "Please use <polygraphy surgeon prune> to rewrite the weights to a sparsity pattern "
<< "and then run with --sparsity=enable" << std::endl;
}
return search->second;
}
template <>
WeightStreamingBudget stringToValue<WeightStreamingBudget>(std::string const& option)
{
WeightStreamingBudget budget;
if (option.find('%') != std::string::npos)
{
double percent = std::stod(option);
if (!(percent >= 0 && percent <= 100.0))
{
std::ostringstream err;
err << "The weight streaming percent must be between 0 and 100.";
throw std::invalid_argument(err.str());
}
budget.percent = percent;
}
else
{
double bytes = stringToValue<double>(option);
if (!(bytes == WeightStreamingBudget::kAUTOMATIC || bytes >= WeightStreamingBudget::kDISABLE))
{
std::ostringstream err;
err << "The weight streaming budget must be " << WeightStreamingBudget::kAUTOMATIC << " or at least "
<< WeightStreamingBudget::kDISABLE << ".";
throw std::invalid_argument(err.str());
}
budget.bytes = static_cast<int64_t>(bytes);
}
return budget;
}
template <typename T>
std::pair<std::string, T> splitNameAndValue(const std::string& s)
{
std::string tensorName;
std::string valueString;
// Support 'inputName':Path format for --loadInputs flag when dealing with Windows paths.
// i.e. 'inputName':c:\inputData
std::vector<std::string> quoteNameRange{ splitToStringVec(s, '\'') };
// splitToStringVec returns the entire string when delimiter is not found, so it's size is always at least 1
if (quoteNameRange.size() != 1)
{
if (quoteNameRange.size() != 3)
{
std::string errorMsg = std::string("Found invalid number of \'s when parsing ") + s +
std::string(". Expected: 2, received: ") + std::to_string(quoteNameRange.size() -1) +
". Please ensure that a singular comma is used within each comma-separated key-value pair for options like --inputIOFormats, --optShapes, --optShapesCalib, --layerPrecisions, etc.";
throw std::invalid_argument(errorMsg);
}
// Everything before the second "'" is the name.
tensorName = quoteNameRange[0] + quoteNameRange[1];
// Path is the last string - ignoring leading ":" so slice it with [1:]
valueString = quoteNameRange[2].substr(1);
return std::pair<std::string, T>(tensorName, stringToValue<T>(valueString));
}
// Split on the last :
std::vector<std::string> nameRange{splitToStringVec(s, ':')};
// Everything before the last : is the name
tensorName = nameRange[0];
for (size_t i = 1; i < nameRange.size() - 1; i++)
{
tensorName += ":" + nameRange[i];
}
// Value is the string element after the last :
valueString = nameRange[nameRange.size() - 1];
return std::pair<std::string, T>(tensorName, stringToValue<T>(valueString));
}
template <typename T>
void splitInsertKeyValue(const std::vector<std::string>& kvList, T& map)
{
for (const auto& kv : kvList)
{
map.insert(splitNameAndValue<typename T::mapped_type>(kv));
}
}
const char* boolToEnabled(bool enable)
{
return enable ? "Enabled" : "Disabled";
}
//! A helper function similar to sep.join(list) in Python.
template <typename T>
std::string joinValuesToString(std::vector<T> const& list, std::string const& sep)
{
std::ostringstream os;
for (int32_t i = 0, n = list.size(); i < n; ++i)
{
os << list[i];
if (i != n - 1)
{
os << sep;
}
}
return os.str();
}
template <typename T, size_t N>
std::string joinValuesToString(std::array<T, N> const& list, std::string const& sep)
{
return joinValuesToString(std::vector<T>(list.begin(), list.end()), sep);
}
//! Check if input option exists in input arguments.
//! If it does: set its value, and return true
//! If it does not: return false.
template <typename T>
bool getOption(Arguments& arguments, const std::string& option, T& value)
{
auto const match = arguments.find(option);
if (match != arguments.end())
{
value = stringToValue<T>(match->second.first);
return true;
}
return false;
}
//! Check if input option exists in input arguments.
//! If it does: set its value, erase the argument and return true.
//! If it does not: return false.
template <typename T_>
bool getAndDelOption(Arguments& arguments, const std::string& option, T_& value)
{
bool found = getOption(arguments, option, value);
if (found)
{
const auto match = arguments.find(option);
arguments.erase(match);
}
return found;
}
//! Check if input option exists in input arguments.
//! If it does: set its value and position, erase the argument and return true.
//! If it does not: return false.
template <typename T_>
bool getAndDelOptionWithPosition(Arguments& arguments, std::string const& option, T_& value, int32_t& pos)
{
auto const match = arguments.find(option);
if (match != arguments.end())
{
value = stringToValue<T_>(match->second.first);
pos = match->second.second;
arguments.erase(match);
return true;
}
return false;
}
//! Check if input option exists in input arguments behind the position spcecified by pos.
//! If it does: set its value, erase the argument and return true.
//! If it does not: return false.
template <typename T_>
bool getAndDelOptionBehind(Arguments& arguments, std::string const& option, int32_t pos, T_& value)
{
auto const match = arguments.equal_range(option);
if (match.first == match.second)
{
return false;
}
for (auto i = match.first; i != match.second; ++i)
{
if (i->second.second - pos == 1)
{
value = stringToValue<T_>(i->second.first);
arguments.erase(i);
return true;
}
}
return false;
}
//! Check if input option exists in input arguments.
//! If it does: set false in value, erase the argument and return true.
//! If it does not: return false.
bool getAndDelNegOption(Arguments& arguments, const std::string& option, bool& value)
{
bool dummy;
if (getAndDelOption(arguments, option, dummy))
{
value = false;
return true;
}
return false;
}
//! Check if input option exists in input arguments.
//! If it does: add all the matched arg values to values vector, erase the argument and return true.
//! If it does not: return false.
template <typename T>
bool getAndDelRepeatedOption(Arguments& arguments, const std::string& option, std::vector<T>& values)
{
const auto match = arguments.equal_range(option);
if (match.first == match.second)
{
return false;
}
auto addToValues
= [&values](Arguments::value_type& argValue) { values.emplace_back(stringToValue<T>(argValue.second.first)); };
std::for_each(match.first, match.second, addToValues);
arguments.erase(match.first, match.second);
return true;
}
void insertShapesBuild(BuildOptions::ShapeProfile& shapes, nvinfer1::OptProfileSelector selector,
const std::string& name, const std::vector<int32_t>& dims)
{
shapes[name][static_cast<size_t>(selector)] = dims;
}
void insertShapesInference(
InferenceOptions::ShapeProfile& shapes, std::string const& name, std::vector<int32_t> const& dims)
{
shapes[name] = dims;
}
std::string removeSingleQuotationMarks(std::string& str)
{
std::vector<std::string> strList{splitToStringVec(str, '\'')};
// Remove all the escaped single quotation marks
std::string retVal;
// Do not really care about unterminated sequences
for (size_t i = 0; i < strList.size(); i++)
{
retVal += strList[i];
}
return retVal;
}
void getLayerPrecisions(Arguments& arguments, char const* argument, LayerPrecisions& layerPrecisions)
{
std::string list;
if (!getAndDelOption(arguments, argument, list))
{
return;
}
// The layerPrecisions flag contains comma-separated layerName:precision pairs.
std::vector<std::string> precisionList{splitToStringVec(list, ',')};
for (auto const& s : precisionList)
{
auto namePrecisionPair = splitNameAndValue<nvinfer1::DataType>(s);
auto const layerName = removeSingleQuotationMarks(namePrecisionPair.first);
layerPrecisions[layerName] = namePrecisionPair.second;
}
}
void getLayerOutputTypes(Arguments& arguments, char const* argument, LayerOutputTypes& layerOutputTypes)
{
std::string list;
if (!getAndDelOption(arguments, argument, list))
{
return;
}
// The layerOutputTypes flag contains comma-separated layerName:types pairs.
std::vector<std::string> precisionList{splitToStringVec(list, ',')};
for (auto const& s : precisionList)
{
auto namePrecisionPair = splitNameAndValue<std::string>(s);
auto const layerName = removeSingleQuotationMarks(namePrecisionPair.first);
auto const typeStrings = splitToStringVec(namePrecisionPair.second, '+');
std::vector<nvinfer1::DataType> typeVec(typeStrings.size(), nvinfer1::DataType::kFLOAT);
std::transform(typeStrings.begin(), typeStrings.end(), typeVec.begin(), stringToValue<nvinfer1::DataType>);
layerOutputTypes[layerName] = typeVec;
}
}
void getLayerDeviceTypes(Arguments& arguments, char const* argument, LayerDeviceTypes& layerDeviceTypes)
{
std::string list;
if (!getAndDelOption(arguments, argument, list))
{
return;
}
// The layerDeviceTypes flag contains comma-separated layerName:deviceType pairs.
std::vector<std::string> deviceList{splitToStringVec(list, ',')};
for (auto const& s : deviceList)
{
auto nameDevicePair = splitNameAndValue<std::string>(s);
auto const layerName = removeSingleQuotationMarks(nameDevicePair.first);
layerDeviceTypes[layerName] = stringToValue<nvinfer1::DeviceType>(nameDevicePair.second);
}
}
void getStringsSet(Arguments& arguments, char const* argument, StringSet& stringSet)
{
std::string list;
if (!getAndDelOption(arguments, argument, list))
{
return;
}
// The layerPrecisions flag contains comma-separated layerName:precision pairs.
std::vector<std::string> strings{splitToStringVec(list, ',')};
for (auto const& s : strings)
{
stringSet.insert(s);
}
}
bool getShapesBuild(Arguments& arguments, BuildOptions::ShapeProfile& shapes, char const* argument,
nvinfer1::OptProfileSelector selector)
{
std::string list;
bool retVal = getAndDelOption(arguments, argument, list);
std::vector<std::string> shapeList{splitToStringVec(list, ',')};
for (const auto& s : shapeList)
{
auto nameDimsPair = splitNameAndValue<std::vector<int32_t>>(s);
auto tensorName = removeSingleQuotationMarks(nameDimsPair.first);
auto dims = nameDimsPair.second;
insertShapesBuild(shapes, selector, tensorName, dims);
}
return retVal;
}
bool getShapesInference(Arguments& arguments, InferenceOptions::ShapeProfile& shapes, const char* argument)
{
std::string list;
bool retVal = getAndDelOption(arguments, argument, list);
std::vector<std::string> shapeList{splitToStringVec(list, ',')};
for (const auto& s : shapeList)
{
auto nameDimsPair = splitNameAndValue<std::vector<int32_t>>(s);
auto tensorName = removeSingleQuotationMarks(nameDimsPair.first);
auto dims = nameDimsPair.second;
insertShapesInference(shapes, tensorName, dims);
}
return retVal;
}
void fillShapes(BuildOptions::ShapeProfile& shapes, std::string const& name, ShapeRange const& sourceShapeRange,
nvinfer1::OptProfileSelector minDimsSource, nvinfer1::OptProfileSelector optDimsSource,
nvinfer1::OptProfileSelector maxDimsSource)
{
insertShapesBuild(
shapes, nvinfer1::OptProfileSelector::kMIN, name, sourceShapeRange[static_cast<size_t>(minDimsSource)]);
insertShapesBuild(
shapes, nvinfer1::OptProfileSelector::kOPT, name, sourceShapeRange[static_cast<size_t>(optDimsSource)]);
insertShapesBuild(
shapes, nvinfer1::OptProfileSelector::kMAX, name, sourceShapeRange[static_cast<size_t>(maxDimsSource)]);
}
void processShapes(BuildOptions::ShapeProfile& shapes, bool minShapes, bool optShapes, bool maxShapes, bool calib)
{
// Only accept optShapes only or all three of minShapes, optShapes, maxShapes when calib is set
if (((minShapes || maxShapes) && !optShapes) // minShapes only, maxShapes only, both minShapes and maxShapes
|| (minShapes && !maxShapes && optShapes) // both minShapes and optShapes
|| (!minShapes && maxShapes && optShapes)) // both maxShapes and optShapes
{
if (calib)
{
throw std::invalid_argument(
"Must specify only --optShapesCalib or all of --minShapesCalib, --optShapesCalib, --maxShapesCalib");
}
}
if (!minShapes && !optShapes && !maxShapes)
{
return;
}
BuildOptions::ShapeProfile newShapes;
for (auto& s : shapes)
{
nvinfer1::OptProfileSelector minDimsSource, optDimsSource, maxDimsSource;
minDimsSource = nvinfer1::OptProfileSelector::kMIN;
optDimsSource = nvinfer1::OptProfileSelector::kOPT;
maxDimsSource = nvinfer1::OptProfileSelector::kMAX;
// Populate missing minShapes
if (!minShapes)
{
if (optShapes)
{
minDimsSource = optDimsSource;
sample::gLogWarning << "optShapes is being broadcasted to minShapes for tensor " << s.first
<< std::endl;
}
else
{
minDimsSource = maxDimsSource;
sample::gLogWarning << "maxShapes is being broadcasted to minShapes for tensor " << s.first
<< std::endl;
}
}
// Populate missing optShapes
if (!optShapes)
{
if (maxShapes)
{
optDimsSource = maxDimsSource;
sample::gLogWarning << "maxShapes is being broadcasted to optShapes for tensor " << s.first
<< std::endl;
}
else
{
optDimsSource = minDimsSource;
sample::gLogWarning << "minShapes is being broadcasted to optShapes for tensor " << s.first
<< std::endl;
}
}
// Populate missing maxShapes
if (!maxShapes)
{
if (optShapes)
{
maxDimsSource = optDimsSource;
sample::gLogWarning << "optShapes is being broadcasted to maxShapes for tensor " << s.first
<< std::endl;
}
else
{
maxDimsSource = minDimsSource;
sample::gLogWarning << "minShapes is being broadcasted to maxShapes for tensor " << s.first
<< std::endl;
}
}
fillShapes(newShapes, s.first, s.second, minDimsSource, optDimsSource, maxDimsSource);
}
shapes = newShapes;
}
bool getOptimizationProfiles(
Arguments& arguments, std::vector<BuildOptions::ShapeProfile>& optProfiles, char const* argument)
{
bool retValue{false};
int32_t pos{};
size_t profileIndex{};
auto getShapes
= [](BuildOptions::ShapeProfile& shapes, std::string const& list, nvinfer1::OptProfileSelector selector) {
std::vector<std::string> shapeList{splitToStringVec(list, ',')};
for (auto const& s : shapeList)
{
auto nameDimsPair = splitNameAndValue<std::vector<int32_t>>(s);
auto tensorName = removeSingleQuotationMarks(nameDimsPair.first);
auto dims = nameDimsPair.second;
insertShapesBuild(shapes, selector, tensorName, dims);
}
};
while (getAndDelOptionWithPosition(arguments, argument, profileIndex, pos))
{
BuildOptions::ShapeProfile optProfile{};
bool minShapes{false}, maxShapes{false}, optShapes{false};
for (int32_t i = 0; i < nvinfer1::EnumMax<nvinfer1::OptProfileSelector>(); i++, pos++)
{
std::string value;
if (!minShapes && getAndDelOptionBehind(arguments, "--minShapes", pos, value))
{
minShapes = true;
getShapes(optProfile, value, nvinfer1::OptProfileSelector::kMIN);
}
else if (!maxShapes && getAndDelOptionBehind(arguments, "--maxShapes", pos, value))
{
maxShapes = true;
getShapes(optProfile, value, nvinfer1::OptProfileSelector::kMAX);
}
else if (!optShapes && getAndDelOptionBehind(arguments, "--optShapes", pos, value))
{
optShapes = true;
getShapes(optProfile, value, nvinfer1::OptProfileSelector::kOPT);
}
else
{
break;
}
}
processShapes(optProfile, minShapes, optShapes, maxShapes, false);
if (profileIndex >= optProfiles.size())
{
optProfiles.resize(profileIndex + 1);
}
if (!optProfiles[profileIndex].empty())
{
throw std::invalid_argument("Optimization profile index cannot be the same.");
}
optProfiles[profileIndex] = optProfile;
retValue = true;
}
profileIndex = 0;
for (auto const& optProfile : optProfiles)
{
if (optProfile.empty())
{
throw std::invalid_argument(std::string("Found invalid or missing shape spec at profile index ")
+ std::to_string(profileIndex) + std::string(". "));
}
++profileIndex;
}
return retValue;
}
template <typename T>
void printShapes(std::ostream& os, char const* phase, T const& shapes, int32_t profileIndex)
{
if (shapes.empty())
{
os << "Input " << phase << " shapes: model" << std::endl;
}
else
{
std::string profileString = (profileIndex != -1 && strcmp(phase, "build") == 0)
? "(profile " + std::to_string(profileIndex) + ")"
: "";
for (auto const& s : shapes)
{
os << "Input " << phase << " shape " << profileString << ": " << s.first << "=" << s.second << std::endl;
}
}
}
std::ostream& printTacticSources(
std::ostream& os, nvinfer1::TacticSources enabledSources, nvinfer1::TacticSources disabledSources)
{
if (!enabledSources && !disabledSources)
{
os << "Using default tactic sources";
}
else
{
auto const addSource = [&](uint32_t source, std::string const& name) {
if (enabledSources & source)
{
os << name << " [ON], ";
}
else if (disabledSources & source)
{
os << name << " [OFF], ";
}
};
addSource(1U << static_cast<uint32_t>(nvinfer1::TacticSource::kCUBLAS), "cublas");
addSource(1U << static_cast<uint32_t>(nvinfer1::TacticSource::kCUBLAS_LT), "cublasLt");
addSource(1U << static_cast<uint32_t>(nvinfer1::TacticSource::kCUDNN), "cudnn");
addSource(1U << static_cast<uint32_t>(nvinfer1::TacticSource::kEDGE_MASK_CONVOLUTIONS), "edge mask convolutions");
addSource(1U << static_cast<uint32_t>(nvinfer1::TacticSource::kJIT_CONVOLUTIONS), "JIT convolutions");
}
return os;
}
std::ostream& printPrecision(std::ostream& os, BuildOptions const& options)
{
os << "FP32";
if (options.fp16)
{
os << "+FP16";
}
if (options.bf16)
{
os << "+BF16";
}
if (options.int8)
{
os << "+INT8";
}
if (options.fp8)
{
os << "+FP8";
}
if (options.stronglyTyped)
{
os << " (Strongly Typed)";
}
if (options.precisionConstraints == PrecisionConstraints::kOBEY)
{
os << " (obey precision constraints)";
}
if (options.precisionConstraints == PrecisionConstraints::kPREFER)
{
os << " (prefer precision constraints)";
}
return os;
}
std::ostream& printTempfileControls(std::ostream& os, TempfileControlFlags const tempfileControls)
{
auto getFlag = [&](TempfileControlFlag f) -> char const* {
bool allowed = !!(tempfileControls & (1U << static_cast<int64_t>(f)));
return allowed ? "allow" : "deny";
};
auto const inMemory = getFlag(TempfileControlFlag::kALLOW_IN_MEMORY_FILES);
auto const temporary = getFlag(TempfileControlFlag::kALLOW_TEMPORARY_FILES);
os << "{ in_memory: " << inMemory << ", temporary: " << temporary << " }";
return os;
}
std::ostream& printTimingCache(std::ostream& os, TimingCacheMode const& timingCacheMode)
{
switch (timingCacheMode)
{
case TimingCacheMode::kGLOBAL: os << "global"; break;
case TimingCacheMode::kLOCAL: os << "local"; break;
case TimingCacheMode::kDISABLE: os << "disable"; break;
}
return os;
}
std::ostream& printSparsity(std::ostream& os, BuildOptions const& options)
{
switch (options.sparsity)
{
case SparsityFlag::kDISABLE: os << "Disabled"; break;
case SparsityFlag::kENABLE: os << "Enabled"; break;
case SparsityFlag::kFORCE: os << "Forced"; break;
}
return os;
}
std::ostream& printMemoryPools(std::ostream& os, BuildOptions const& options)
{
auto const printValueOrDefault = [&os](double const val) {
if (val >= 0)
{
os << val << " MiB";
}
else
{
os << "default";
}
};
os << "workspace: ";
printValueOrDefault(options.workspace);
os << ", ";
os << "dlaSRAM: ";
printValueOrDefault(options.dlaSRAM);
os << ", ";
os << "dlaLocalDRAM: ";
printValueOrDefault(options.dlaLocalDRAM);
os << ", ";
os << "dlaGlobalDRAM: ";
printValueOrDefault(options.dlaGlobalDRAM);
os << ", ";
os << "tacticSharedMem: ";
printValueOrDefault(options.tacticSharedMem);
return os;
}
std::string previewFeatureToString(PreviewFeature feature)
{
// clang-format off
switch (feature)
{
case PreviewFeature::kPROFILE_SHARING_0806:
{
gLogWarning << "profileSharing0806 is on by default in TensorRT 10.0. This flag is deprecated and has no effect." << std::endl;
break;
}
}
return "Invalid Preview Feature";
// clang-format on
}
std::ostream& printPreviewFlags(std::ostream& os, BuildOptions const& options)
{
if (options.previewFeatures.empty())
{
os << "Use default preview flags.";
return os;
}
auto const addFlag = [&](PreviewFeature feat) {
int32_t featVal = static_cast<int32_t>(feat);
if (options.previewFeatures.find(featVal) != options.previewFeatures.end())
{
os << previewFeatureToString(feat) << (options.previewFeatures.at(featVal) ? " [ON], " : " [OFF], ");
}
};
// unused
static_cast<void>(addFlag);
return os;
}
} // namespace
Arguments argsToArgumentsMap(int32_t argc, char* argv[])
{
Arguments arguments;
for (int32_t i = 1; i < argc; ++i)
{
auto valuePtr = strchr(argv[i], '=');
if (valuePtr)
{
std::string value{valuePtr + 1};
arguments.emplace(std::string(argv[i], valuePtr - argv[i]), std::make_pair(value, i));
}
else
{
arguments.emplace(argv[i], std::make_pair(std::string(""), i));
}
}
return arguments;
}
namespace
{
std::string resolveHomeDirectoryOnLinux(std::string const& model)
{
std::string filePath{model};
#ifndef _WIN32
if (filePath[0] == '~')
{
char const* home = std::getenv("HOME");
if (home)
{
filePath.replace(0, 1, home);
}
}
#endif
return filePath;
}
} // namespace
void BaseModelOptions::parse(Arguments& arguments)
{
if (getAndDelOption(arguments, "--onnx", model))
{
format = ModelFormat::kONNX;
model = resolveHomeDirectoryOnLinux(model);
}
}
void ModelOptions::parse(Arguments& arguments)
{
baseModel.parse(arguments);
switch (baseModel.format)
{
case ModelFormat::kONNX:
case ModelFormat::kANY:
{
break;
}
}
if (baseModel.format == ModelFormat::kONNX)
{
if (!outputs.empty())
{
throw std::invalid_argument("The --output flag should not be used with ONNX models.");
}
}
}
void getTempfileControls(Arguments& arguments, char const* argument, TempfileControlFlags& tempfileControls)
{
std::string list;
if (!getAndDelOption(arguments, argument, list))
{
return;
}