forked from onnx/onnx-tensorrt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonnx2trt_utils.cpp
1447 lines (1298 loc) · 50.1 KB
/
onnx2trt_utils.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) 2018, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "onnx2trt_utils.hpp"
std::ostream& operator<<(std::ostream& stream, nvinfer1::Dims const& shape) {
if( shape.nbDims == 0 ) {
return stream;
}
stream << "(" << shape.d[0];
for( int i=1; i<shape.nbDims; ++i ) {
stream << ", " << shape.d[i];
}
stream << ")";
return stream;
}
std::ostream& operator<<(std::ostream& stream, nvinfer1::DataType const& dtype) {
switch( dtype ) {
case nvinfer1::DataType::kFLOAT: return stream << "float32";
case nvinfer1::DataType::kHALF: return stream << "float16";
case nvinfer1::DataType::kINT8: return stream << "int8";
case nvinfer1::DataType::kINT32: return stream << "int32";
default: throw std::runtime_error("Unknown dtype");
}
}
std::ostream& operator<<(std::ostream& stream, nvinfer1::Permutation const& perm) {
int ndims = nvinfer1::Dims::MAX_DIMS;
stream << "(" << perm.order[0];
for( int i=1; i<ndims; ++i ) {
stream << ", " << perm.order[i];
}
stream << ")";
return stream;
}
namespace onnx2trt
{
NodeImportResult activationHelper(IImporterContext* ctx, const ::ONNX_NAMESPACE::NodeProto& node,
std::vector<TensorOrWeights>& inputs, nvinfer1::ActivationType op, float* alpha, float* beta)
{
nvinfer1::ITensor& input = convertToTensor(inputs.at(0), ctx);
nvinfer1::IActivationLayer* layer = ctx->network()->addActivation(input, op);
if (alpha)
{
layer->setAlpha(*alpha);
}
if (beta)
{
layer->setBeta(*beta);
}
return {{layer->getOutput(0)}};
}
NodeImportResult addScale(IImporterContext* ctx, nvinfer1::ITensor& tensor_, nvinfer1::ScaleMode mode,
nvinfer1::Weights shift, nvinfer1::Weights scale, nvinfer1::Weights power)
{
nvinfer1::ITensor* tensor_ptr = &tensor_;
nvinfer1::Dims dims = tensor_ptr->getDimensions();
// Scale layer expects inputs to be 4D.
int expectedNbDims = 4;
bool need_to_expand_dims = (dims.nbDims != expectedNbDims);
nvinfer1::Dims orig_shape = dims;
if (need_to_expand_dims)
{
// Expand or squash dims to 4D
nvinfer1::Dims new_shape = dims;
while (new_shape.nbDims < expectedNbDims)
{
new_shape.d[new_shape.nbDims++] = 1;
}
while (new_shape.nbDims > expectedNbDims)
{
new_shape.d[3] *= new_shape.d[--new_shape.nbDims];
}
tensor_ptr = reshape_tensor(ctx, *tensor_ptr, new_shape);
ASSERT(tensor_ptr, ErrorCode::kUNSUPPORTED_NODE);
dims = tensor_ptr->getDimensions();
}
ASSERT(dims.nbDims == expectedNbDims, ErrorCode::kUNSUPPORTED_NODE);
// Fill in dtype for any unused (dummy) weights
nvinfer1::DataType* dtype_ptr = nullptr;
if (shift.count)
{
dtype_ptr = &shift.type;
}
if (scale.count)
{
ASSERT(!dtype_ptr || *dtype_ptr == scale.type, ErrorCode::kUNSUPPORTED_NODE);
dtype_ptr = &scale.type;
}
if (power.count)
{
ASSERT(!dtype_ptr || *dtype_ptr == power.type, ErrorCode::kUNSUPPORTED_NODE);
dtype_ptr = &power.type;
}
ASSERT(dtype_ptr, ErrorCode::kINTERNAL_ERROR);
shift.type = *dtype_ptr;
scale.type = *dtype_ptr;
power.type = *dtype_ptr;
auto* layer = ctx->network()->addScale(*tensor_ptr, mode, shift, scale, power);
ASSERT(layer, ErrorCode::kUNSUPPORTED_NODE);
tensor_ptr = layer->getOutput(0);
if (need_to_expand_dims)
{
tensor_ptr = reshape_tensor(ctx, *tensor_ptr, orig_shape);
ASSERT(tensor_ptr, ErrorCode::kUNSUPPORTED_NODE);
}
return {{tensor_ptr}};
}
void auto_gen_input_output_padding(nvinfer1::Dims input_dims, nvinfer1::Dims output_shape, nvinfer1::Dims kernel_size,
nvinfer1::Dims strides, nvinfer1::Dims dilations, const int nbSpatialDims, nvinfer1::Dims& beg_padding,
nvinfer1::Dims& end_padding, nvinfer1::Dims& output_padding, nvinfer1::PaddingMode paddingMode)
{
// When auto_pad == NONSET or VALID, input padding is explict
// explicit output shape may require output padding
if (paddingMode == nvinfer1::PaddingMode::kEXPLICIT_ROUND_DOWN)
{
nvinfer1::Dims expected_output_shape;
for (int i = 0; i < nbSpatialDims; i++)
{
expected_output_shape.d[i] = (input_dims.d[2 + i] - 1) * strides.d[i]
+ (kernel_size.d[i] - 1) * dilations.d[i] + 1 - beg_padding.d[i] - end_padding.d[i];
output_padding.d[i] = output_shape.d[i] - expected_output_shape.d[i];
}
}
else
{
// When auto_pad == SAME_UPPER or SAME_LOWER, output padding is explict
// explicit output shape may require input padding
nvinfer1::Dims total_padding = makeDims(nbSpatialDims, 0);
for (int i = 0; i < nbSpatialDims; i++)
{
total_padding.d[i] = (input_dims.d[2 + i] - 1) * strides.d[i] + (kernel_size.d[i] - 1) * dilations.d[i] + 1
+ output_padding.d[i] - output_shape.d[i];
if (paddingMode == nvinfer1::PaddingMode::kSAME_UPPER)
{
beg_padding.d[i] = total_padding.d[i] - (total_padding.d[i] / 2);
end_padding.d[i] = total_padding.d[i] / 2;
}
else
{
beg_padding.d[i] = total_padding.d[i] / 2;
end_padding.d[i] = total_padding.d[i] - (total_padding.d[i] / 2);
}
}
}
}
Status applyLegacyBinaryOpBroadcasting(IImporterContext* ctx,
::ONNX_NAMESPACE::NodeProto const& node,
TensorOrWeights& lhs,
TensorOrWeights& rhs) {
int lhs_ndim = lhs.shape().nbDims;
int rhs_ndim = rhs.shape().nbDims;
OnnxAttrs attrs(node);
bool broadcasting_on = (attrs.count("axis") && attrs.count("broadcast") &&
attrs.get<int>("broadcast"));
if (rhs_ndim >= lhs_ndim || !broadcasting_on)
{
return Status::success();
}
int axis = attrs.get<int>("axis");
if( axis < 0 )
{
axis += lhs_ndim; // Support negative indexing
}
int num_dims_to_add_at_end = lhs_ndim - rhs_ndim - axis;
ASSERT(num_dims_to_add_at_end >= 0, ErrorCode::kINVALID_NODE);
nvinfer1::Dims new_shape;
new_shape.nbDims = 0;
for (int i = 0; i < axis; i++)
{
new_shape.d[new_shape.nbDims++] = 1;
}
for (int i = 0; i < rhs_ndim; i++)
{
new_shape.d[new_shape.nbDims++] = rhs.shape().d[i];
}
for (int i=0; i<num_dims_to_add_at_end; ++i)
{
new_shape.d[new_shape.nbDims++] = 1;
}
if (rhs.is_weights())
{
rhs.weights().shape = new_shape;
}
else
{
ASSERT(rhs.reset_tensor(reshape_tensor(ctx, rhs.tensor(), new_shape)),
ErrorCode::kUNSUPPORTED_NODE);
}
return Status::success();
}
NodeImportResult argMinMaxHelper(IImporterContext* ctx, const ::ONNX_NAMESPACE::NodeProto& node,
std::vector<TensorOrWeights>& inputs, nvinfer1::TopKOperation op)
{
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
ASSERT(tensorPtr->getType() != nvinfer1::DataType::kINT32, ErrorCode::kUNSUPPORTED_NODE);
// Support 1D argMin/argMax
bool needToExpandDims = (tensorPtr->getDimensions().nbDims == 1);
if (needToExpandDims)
{
// Expand dims from 1D to 2D
std::vector<int> axes{1};
tensorPtr = unsqueezeTensor(ctx, *tensorPtr, axes);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
}
// Get attributes.
OnnxAttrs attrs(node);
int keepdims = attrs.get("keepdims", 1);
int axis = attrs.get("axis", 0);
// Insert a TopK layer with k set to 1.
int nbDims = tensorPtr->getDimensions().nbDims;
TRT_CHECK(convert_axis(axis, nbDims));
uint32_t axisMask = 1 << axis;
nvinfer1::ITopKLayer* layer = ctx->network()->addTopK(*tensorPtr, op, 1, axisMask);
ASSERT(layer, ErrorCode::kUNSUPPORTED_NODE);
// We don't care about the TopK values, just the indices.
nvinfer1::ITensor* indices = layer->getOutput(1);
indices->setType(nvinfer1::DataType::kINT32);
// Squeeze back to 1D if applicable
if (needToExpandDims)
{
std::vector<int> axes{1};
indices = squeezeTensor(ctx, *indices, axes);
ASSERT(indices, ErrorCode::kUNSUPPORTED_NODE);
}
// The default behavior of the TopK layer is to keepdims.
if (keepdims)
{
return {{indices}};
}
else
{
// Otherwise, we need to squeeze the axis dimension
std::vector<int> axes{axis};
indices = squeezeTensor(ctx, *indices, axes);
return {{indices}};
}
}
void broadcastTensors(IImporterContext* ctx, nvinfer1::ITensor*& t1, const int nbDims)
{
nvinfer1::Dims inputDims = t1->getDimensions();
int nbInputDims = inputDims.nbDims;
if (nbInputDims >= nbDims)
{
return;
}
int numLeadingDims = nbDims - nbInputDims;
// Perform broadcasting by unsqueezing input tensor on axes [0...numLeadingDims - 1]
if (nbInputDims > 0)
{
std::vector<int> axes(numLeadingDims);
std::iota(axes.begin(), axes.end(), 0);
t1 = unsqueezeTensor(ctx, *t1, axes);
}
// Handle scalar inputs by reshaping to shape of rank numLeadingDims.
else
{
auto* reshapeLayer = ctx->network()->addShuffle(*t1);
reshapeLayer->setReshapeDimensions(makeDims(numLeadingDims, 1));
t1 = reshapeLayer->getOutput(0);
}
}
void broadcastTensors(IImporterContext* ctx, nvinfer1::ITensor*& t1, nvinfer1::ITensor*& t2)
{
const int t1Dims = t1->getDimensions().nbDims;
const int t2Dims = t2->getDimensions().nbDims;
if (t1Dims == t2Dims)
{
return;
}
if (t1Dims > t2Dims)
{
broadcastTensors(ctx, t2, t1Dims);
}
else
{
broadcastTensors(ctx, t1, t2Dims);
}
}
Status check_broadcast_attrs(IImporterContext* ctx, OnnxAttrs const& attrs, nvinfer1::Dims const& dims)
{
if (ctx->getOpsetVersion() < 7)
{
ASSERT(attrs.count("broadcast"), ErrorCode::kUNSUPPORTED_NODE);
bool broadcast = attrs.get<int>("broadcast");
ASSERT(broadcast || dims.nbDims == 1, ErrorCode::kINVALID_NODE);
int axis = attrs.get<int>("axis", -1);
int nbDims = dims.nbDims;
TRT_CHECK(convert_axis(axis, nbDims));
ASSERT(axis == 0, ErrorCode::kUNSUPPORTED_NODE);
}
return Status::success();
}
bool check_for_input(::ONNX_NAMESPACE::NodeProto const& node, std::string const& input_node)
{
for (auto input : node.input())
{
if (input_node == input)
{
return true;
}
}
return false;
}
bool check_for_int32(std::vector<TensorOrWeights>const & inputs)
{
bool isInt32 = false;
for (auto input : inputs)
{
if (input.is_weights())
{
nvinfer1::DataType dt;
convert_dtype(input.weights().type, &dt);
isInt32 |= dt == nvinfer1::DataType::kINT32;
}
else
{
isInt32 |= input.tensor().getType() == nvinfer1::DataType::kINT32;
}
}
return isInt32;
}
bool check_for_scale(std::vector<TensorOrWeights>const & inputs)
{
bool useScale = true;
// Inputs cannot be int32.
useScale &= !(check_for_int32(inputs));
// One input must be a tensor and the other one must be a weight.
useScale &= inputs.at(0).is_tensor() != inputs.at(1).is_tensor();
// Tensor input must be at least 4D.
if (useScale)
{
const nvinfer1::ITensor& tensor = inputs.at(0).is_tensor() ? inputs.at(0).tensor() : inputs.at(1).tensor();
useScale &= tensor.getDimensions().nbDims >= 4;
}
return useScale;
}
Status convert_axis(int& axis, int nbDims)
{
// Support negative indexing
if (axis < 0)
{
axis += nbDims;
}
ASSERT(axis >= 0 && axis < nbDims, ErrorCode::kUNSUPPORTED_NODE);
return Status::success();
}
bool convert_dtype(int32_t onnx_dtype, nvinfer1::DataType* trt_dtype)
{
switch( onnx_dtype )
{
case ::ONNX_NAMESPACE::TensorProto::FLOAT: *trt_dtype = nvinfer1::DataType::kFLOAT; break;
case ::ONNX_NAMESPACE::TensorProto::INT8: *trt_dtype = nvinfer1::DataType::kINT8; break;
case ::ONNX_NAMESPACE::TensorProto::FLOAT16: *trt_dtype = nvinfer1::DataType::kHALF; break;
// See ShapedWeights.cpp for sanity check if all values can be safetly downcasted to INT32
case ::ONNX_NAMESPACE::TensorProto::INT64: *trt_dtype = nvinfer1::DataType::kINT32; break;
case ::ONNX_NAMESPACE::TensorProto::INT32: *trt_dtype = nvinfer1::DataType::kINT32; break;
default:
cerr << "Unsupported ONNX data type: " << get_dtype_name(onnx_dtype)
<< " (" << std::to_string(onnx_dtype) << ")" << endl;
return false;
}
return true;
}
bool convert_input_dtype(int32_t onnx_dtype, nvinfer1::DataType* trt_dtype)
{
switch( onnx_dtype )
{
case ::ONNX_NAMESPACE::TensorProto::FLOAT: *trt_dtype = nvinfer1::DataType::kFLOAT; break;
case ::ONNX_NAMESPACE::TensorProto::INT8: *trt_dtype = nvinfer1::DataType::kINT8; break;
case ::ONNX_NAMESPACE::TensorProto::FLOAT16: *trt_dtype = nvinfer1::DataType::kHALF; break;
case ::ONNX_NAMESPACE::TensorProto::INT32: *trt_dtype = nvinfer1::DataType::kINT32; break;
default:
cerr << "Unsupported ONNX data type: " << get_dtype_name(onnx_dtype)
<< " (" << std::to_string(onnx_dtype) << ")" << endl;
return false;
}
return true;
}
bool convert_onnx_weights(::ONNX_NAMESPACE::TensorProto const& onnx_tensor, onnx2trt::ShapedWeights* weights)
{
nvinfer1::Dims shape;
shape.nbDims = onnx_tensor.dims().size();
std::copy(onnx_tensor.dims().begin(), onnx_tensor.dims().end(), shape.d);
auto const& onnx_tensor_type = onnx_tensor.data_type();
void* data_ptr; // TODO: See if can make const*
size_t nbytes;
if( onnx_tensor.raw_data().size() > 0 )
{
data_ptr = (void*)onnx_tensor.raw_data().data();
nbytes = onnx_tensor.raw_data().size();
}
else if( onnx_tensor.float_data().size() > 0 )
{
assert(onnx_tensor_type == ::ONNX_NAMESPACE::TensorProto::FLOAT);
data_ptr = (void*)onnx_tensor.float_data().data();
nbytes = onnx_tensor.float_data().size() * sizeof(float);
}
else if( onnx_tensor.int32_data().size() > 0 )
{
// TODO: Need special handling for int8 or float16 stored as int32_data
assert(get_dtype_size(onnx_tensor_type) == 4);
data_ptr = (void*)onnx_tensor.int32_data().data();
nbytes = onnx_tensor.int32_data().size() * sizeof(int32_t);
}
else if( onnx_tensor.int64_data().size() > 0 )
{
assert(onnx_tensor_type == ::ONNX_NAMESPACE::TensorProto::INT64);
data_ptr = (void*)onnx_tensor.int64_data().data();
nbytes = onnx_tensor.int64_data().size() * sizeof(int64_t);
}
else
{
// Unsupported ONNX tensor format!
return false;
}
// nvinfer1::DataType trt_dtype;
// convert_dtype(onnx_tensor_type, &trt_dtype);
onnx2trt::ShapedWeights trt_weights(onnx_tensor_type, data_ptr, shape);
(void)nbytes;
assert(trt_weights.size_bytes() == nbytes);
*weights = trt_weights;
return true;
}
nvinfer1::ITensor& convert_output_weight_to_tensor(TensorOrWeights& input, IImporterContext* ctx)
{
if (input.is_tensor())
{
return input.tensor();
}
else
{
const ShapedWeights& weights = input.weights();
nvinfer1::Dims tensor_shape = weights.shape;
return *(ctx->network()->addConstant(tensor_shape, weights)->getOutput(0));
}
}
nvinfer1::ITensor* convert_tensor_to_2d(IImporterContext* ctx, nvinfer1::ITensor& tensor, int axis = 0)
{
nvinfer1::Dims shape = tensor.getDimensions();
nvinfer1::Dims new_shape = makeDims(2, 1);
for (int i = 0; i < axis; ++i)
{
new_shape.d[0] *= shape.d[i];
}
for (int i = axis; i < shape.nbDims; ++i)
{
new_shape.d[1] *= shape.d[i];
}
return reshape_tensor(ctx, tensor, new_shape);
}
bool convert_weight_descriptor(onnxTensorDescriptorV1 const &desc, onnx2trt::ShapedWeights *weights)
{
nvinfer1::Dims shape;
shape.nbDims = desc.dimensions;
// Special case for scalars
if( shape.nbDims == 0 ) {
shape.nbDims = 1;
shape.d[0] = 1;
shape.type[0] = nvinfer1::DimensionType::kCHANNEL;
} else {
std::copy(desc.shape, desc.shape + desc.dimensions, shape.d);
}
size_t element_count = 1;
for (int i = 0; i < shape.nbDims; ++i) {
element_count *= shape.d[i];
}
void* data_ptr;
size_t nbytes;
int32_t dtype;
data_ptr = (void*)(desc. buffer);
if (desc.dataType == ONNXIFI_DATATYPE_FLOAT32) {
dtype = ::ONNX_NAMESPACE::TensorProto::FLOAT;
nbytes = element_count * sizeof(float);
} else if (desc.dataType == ONNXIFI_DATATYPE_FLOAT16) {
dtype = ::ONNX_NAMESPACE::TensorProto::FLOAT16;
nbytes = element_count * sizeof(float) / 2;
} else if (desc.dataType == ONNXIFI_DATATYPE_INT32) {
dtype = ::ONNX_NAMESPACE::TensorProto::INT32;
nbytes = element_count * sizeof(int32_t);
} else if (desc.dataType == ONNXIFI_DATATYPE_INT64) {
dtype = ::ONNX_NAMESPACE::TensorProto::INT64;
nbytes = element_count * sizeof(int64_t);
} else {
// Unsupported format
return false;
}
onnx2trt::ShapedWeights trt_weights(dtype, data_ptr, shape);
(void)nbytes;
assert(trt_weights.size_bytes() == nbytes);
*weights = trt_weights;
return true;
}
nvinfer1::ITensor& convertToTensor(TensorOrWeights& input, IImporterContext* ctx)
{
if (input.is_tensor())
{
return input.tensor();
}
else
{
// Handle non-tensor indices input by adding a new constant layer to the network.
const ShapedWeights& weights = input.weights();
return *(ctx->network()->addConstant(weights.shape, weights)->getOutput(0));
}
}
nvinfer1::ITensor& dimension_to_tensor(IImporterContext* ctx, nvinfer1::Dims dims)
{
ShapedWeights temp_weights = ctx->createTempWeights(::ONNX_NAMESPACE::TensorProto_DataType_INT32, nvinfer1::Dims{1, {dims.nbDims}});
std::vector<int> data(dims.d, dims.d+dims.nbDims);
std::copy(data.begin(), data.end(), static_cast<int*>(temp_weights.values));
TensorOrWeights w(temp_weights);
nvinfer1::ITensor& input = convertToTensor(w, ctx);
return input;
}
int div_ceil(int n, int d)
{
return (n - 1) / d + 1;
}
NodeImportResult elementwiseHelper(IImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node,
std::vector<TensorOrWeights>& inputs, nvinfer1::ElementWiseOperation binary_op)
{
ASSERT(!inputs.empty(), ErrorCode::kINVALID_NODE);
std::vector<nvinfer1::ITensor*> inputTensors;
int maxNbDims = -1;
for (auto input : inputs)
{
maxNbDims = std::max(maxNbDims, input.shape().nbDims);
}
for (auto input: inputs)
{
nvinfer1::ITensor* tensor_ptr;
if (input.shape().nbDims == 0 && input.is_weights())
{
if (input.weights().type == ::ONNX_NAMESPACE::TensorProto::INT32 || input.weights().type == ::ONNX_NAMESPACE::TensorProto::INT64)
{
int32_t index = static_cast<int32_t*>(input.weights().values)[0];
tensor_ptr = addConstantScalar<int32_t>(ctx, static_cast<int32_t>(index), ::ONNX_NAMESPACE::TensorProto::INT32)->getOutput(0);
}
else
{
float index = static_cast<float*>(input.weights().values)[0];
tensor_ptr = addConstantScalar<float>(ctx, static_cast<float>(index), ::ONNX_NAMESPACE::TensorProto::FLOAT)->getOutput(0);
}
}
else
{
tensor_ptr = &convertToTensor(input, ctx);
}
// Broadcast all input tensors to size of maxNbDims
broadcastTensors(ctx, tensor_ptr, maxNbDims);
ASSERT(tensor_ptr->getDimensions().nbDims == maxNbDims && "Failed to broadcast tensors elementwise!",
ErrorCode::kUNSUPPORTED_NODE);
inputTensors.push_back(tensor_ptr);
}
// Use the first tensor input as the base for the elementwise operation
nvinfer1::ITensor* combined = inputTensors.at(0);
if (inputTensors.size() == 1)
{
// Note: Single input must be wrapped in identity to avoid messing up network outputs
return {{identity(ctx, combined)}};
}
for (size_t i = 1; i < inputTensors.size(); ++i)
{
nvinfer1::ITensor* tensor = inputTensors.at(i);
ASSERT(tensor->getDimensions().nbDims == combined->getDimensions().nbDims, ErrorCode::kUNSUPPORTED_NODE);
auto* layer = ctx->network()->addElementWise(*combined, *tensor, binary_op);
ASSERT(layer, ErrorCode::kUNSUPPORTED_NODE);
combined = layer->getOutput(0);
}
return {{combined}};
}
nvinfer1::ITensor* flattenTensorDynamic(IImporterContext* ctx, nvinfer1::ITensor& tensor, int axis)
{
nvinfer1::Dims dims = tensor.getDimensions();
auto* shape = ctx->network()->addShape(tensor)->getOutput(0);
// Gather "start indicies" in a loop and multiply them together to get the "start shape"
// Do the same for the "axis indices" and then concat them together.
nvinfer1::ITensor* startTensor;
nvinfer1::ITensor* axisTensor;
nvinfer1::Dims singleDim = makeDims(1, 1);
// If axis is 0, startTensor is a single 1.
if (axis == 0)
{
startTensor = &makeShapeTensor(ctx, singleDim);
}
else
{
std::vector<int> startIndex {0};
auto* startLayer = ctx->network()->addGather(*shape, *addConstant(ctx, startIndex, ::ONNX_NAMESPACE::TensorProto::INT32, singleDim)->getOutput(0), 0);
startTensor = startLayer->getOutput(0);
for (int i = 1; i < axis; i++)
{
startIndex = {i};
auto* beforeLayer = ctx->network()->addGather(*shape, *addConstant(ctx, startIndex, ::ONNX_NAMESPACE::TensorProto::INT32, singleDim)->getOutput(0), 0);
auto* before = beforeLayer->getOutput(0);
startTensor = ctx->network()->addElementWise(*startTensor, *before, nvinfer1::ElementWiseOperation::kPROD)->getOutput(0);
}
}
std::vector<int> axisIndex {axis};
auto* axisLayer = ctx->network()->addGather(*shape, *addConstant(ctx, axisIndex, ::ONNX_NAMESPACE::TensorProto::INT32, singleDim)->getOutput(0), 0);
axisTensor = axisLayer->getOutput(0);
for (int i = axis + 1; i < dims.nbDims; i++)
{
axisIndex = {i};
auto* afterLayer = ctx->network()->addGather(*shape, *addConstant(ctx, axisIndex, ::ONNX_NAMESPACE::TensorProto::INT32, singleDim)->getOutput(0), 0);
auto* after = afterLayer->getOutput(0);
axisTensor = ctx->network()->addElementWise(*axisTensor, *after, nvinfer1::ElementWiseOperation::kPROD)->getOutput(0);
}
std::vector<nvinfer1::ITensor*> tensors{startTensor, axisTensor};
auto* concatLayer = ctx->network()->addConcatenation(tensors.data(), tensors.size());
auto* reshapeLayer = ctx->network()->addShuffle(tensor);
reshapeLayer->setInput(1, *concatLayer->getOutput(0));
return reshapeLayer->getOutput(0);
}
nvinfer1::ITensor* flattenTensorStatic(IImporterContext* ctx, nvinfer1::ITensor& tensor, int axis)
{
nvinfer1::Dims dims = tensor.getDimensions();
nvinfer1::Dims flattenDims = makeDims(2, 1);
if (axis != 0)
{
flattenDims.d[0] = std::accumulate(dims.d, dims.d + axis, 1, std::multiplies<int>());
}
flattenDims.d[1] = std::accumulate(dims.d + axis, dims.d + dims.nbDims, 1, std::multiplies<int>());
auto* flattenLayer = ctx->network()->addShuffle(tensor);
flattenLayer->setReshapeDimensions(flattenDims);
return flattenLayer->getOutput(0);
}
nvinfer1::ITensor* flattenTensor(IImporterContext* ctx, nvinfer1::ITensor& tensor, int axis)
{
if (isDynamic(tensor.getDimensions()))
{
return flattenTensorDynamic(ctx, tensor, axis);
}
return flattenTensorStatic(ctx, tensor, axis);
}
nvinfer1::ITensor* gatherDimension(IImporterContext* ctx, nvinfer1::ITensor* shapeTensor, int dim, nvinfer1::Dims shape)
{
auto& axisValue = *addConstantScalar(ctx, dim, ::ONNX_NAMESPACE::TensorProto_DataType_INT32, shape)->getOutput(0);
return ctx->network()->addGather(*shapeTensor, axisValue, 0)->getOutput(0);
}
bool isDynamic(nvinfer1::Dims const& dims)
{
return std::any_of(dims.d, dims.d + dims.nbDims, [](int dim) {return dim == -1;});
}
nvinfer1::IPluginV2* importPluginFromRegistry(IImporterContext* ctx, const std::string& pluginName,
const std::string& pluginVersion, const std::string& nodeName, const std::vector<nvinfer1::PluginField>& pluginFields)
{
const auto mPluginRegistry = getPluginRegistry();
const auto pluginCreator = mPluginRegistry->getPluginCreator(pluginName.c_str(), pluginVersion.c_str(), "ONNXTRT_NAMESPACE");
if (!pluginCreator)
{
return nullptr;
}
nvinfer1::PluginFieldCollection fc;
fc.nbFields = pluginFields.size();
fc.fields = pluginFields.data();
return pluginCreator->createPlugin(nodeName.c_str(), &fc);
}
bool is_transpose_required(nvinfer1::Dims const& shape, nvinfer1::Permutation const& perm)
{
int ndim = shape.nbDims;
int prev_significant_dim = 0;
for (int dst_i = 0; dst_i < ndim; ++dst_i)
{
int src_i = perm.order[dst_i];
int dim_i = shape.d[src_i];
if (dim_i != 1)
{
// For transposes on dynamically shaped tensors, we must return true.
if (dim_i == -1)
{
return true;
}
else if (src_i < prev_significant_dim)
{
return true;
}
prev_significant_dim = src_i;
}
}
return false;
}
nvinfer1::ITensor* getAxisLength(IImporterContext* ctx, nvinfer1::ITensor* inpTensor, int axis, nvinfer1::Dims shape)
{
// fast path for static dims
auto dims = inpTensor->getDimensions();
int d = dims.d[axis];
if (d >= 0)
{
return addConstantScalar(ctx, d, ::ONNX_NAMESPACE::TensorProto_DataType_INT32, shape)->getOutput(0);
}
else
{
auto& inpShape = *ctx->network()->addShape(*inpTensor)->getOutput(0);
auto& axisValue = *addConstantScalar(ctx, axis, ::ONNX_NAMESPACE::TensorProto_DataType_INT32, shape)->getOutput(0);
return ctx->network()->addGather(inpShape, axisValue, 0)->getOutput(0);
}
}
int get_conv_output_size(int input_size, int filter_size,
int stride, int dilation_rate,
int total_padding)
{
// This is based on the CUDNN formula
int effective_input_size = input_size + total_padding;
int effective_filter_size = (filter_size - 1) * dilation_rate + 1;
return div_ceil(effective_input_size - (effective_filter_size - 1), stride);
}
const char* get_dtype_name(int32_t onnx_dtype) {
switch( onnx_dtype ) {
case ::ONNX_NAMESPACE::TensorProto::FLOAT: return "FLOAT";
case ::ONNX_NAMESPACE::TensorProto::UINT8: return "UINT8";
case ::ONNX_NAMESPACE::TensorProto::INT8: return "INT8";
case ::ONNX_NAMESPACE::TensorProto::UINT16: return "UINT16";
case ::ONNX_NAMESPACE::TensorProto::INT16: return "INT16";
case ::ONNX_NAMESPACE::TensorProto::INT32: return "INT32";
case ::ONNX_NAMESPACE::TensorProto::INT64: return "INT64";
case ::ONNX_NAMESPACE::TensorProto::STRING: return "STRING";
case ::ONNX_NAMESPACE::TensorProto::BOOL: return "BOOL";
case ::ONNX_NAMESPACE::TensorProto::FLOAT16: return "FLOAT16";
case ::ONNX_NAMESPACE::TensorProto::DOUBLE: return "DOUBLE";
case ::ONNX_NAMESPACE::TensorProto::UINT32: return "UINT32";
case ::ONNX_NAMESPACE::TensorProto::UINT64: return "UINT64";
case ::ONNX_NAMESPACE::TensorProto::COMPLEX64: return "COMPLEX64";
case ::ONNX_NAMESPACE::TensorProto::COMPLEX128: return "COMPLEX128";
default: return "<UNKNOWN>";
}
}
int get_dtype_size(int32_t onnx_dtype) {
switch( onnx_dtype ) {
case ::ONNX_NAMESPACE::TensorProto::FLOAT16: return 2;
case ::ONNX_NAMESPACE::TensorProto::FLOAT: return 4;
case ::ONNX_NAMESPACE::TensorProto::DOUBLE: return 8;
case ::ONNX_NAMESPACE::TensorProto::COMPLEX64: return 8;
case ::ONNX_NAMESPACE::TensorProto::COMPLEX128: return 16;
case ::ONNX_NAMESPACE::TensorProto::UINT8: return 1;
case ::ONNX_NAMESPACE::TensorProto::INT8: return 1;
case ::ONNX_NAMESPACE::TensorProto::UINT16: return 2;
case ::ONNX_NAMESPACE::TensorProto::INT16: return 2;
case ::ONNX_NAMESPACE::TensorProto::UINT32: return 4;
case ::ONNX_NAMESPACE::TensorProto::INT32: return 4;
case ::ONNX_NAMESPACE::TensorProto::UINT64: return 8;
case ::ONNX_NAMESPACE::TensorProto::INT64: return 8;
// TODO: Add BOOL if necessary...
// TODO: Some sort of error handling
default: return -1;//throw std::invalid_argument("Unsupported TRT data type: " +
// std::to_string((int)trt_dtype));
}
}
Status get_infer_dim(int& infer_dim, nvinfer1::Dims const& new_shape)
{
for (int i = 0; i < new_shape.nbDims; ++i)
{
if (new_shape.d[i] < 0)
{
// -1 bears special meaning, which means the current dimension can
// be inferred while keepin the total number of elements the same.
// https://github.com/onnx/onnx/blob/9b9f595107e3fc0295d50f6294d43879df17552f/onnx/defs/tensor/defs.cc#L73-L75
ASSERT(new_shape.d[i] == -1, ErrorCode::kUNSUPPORTED_NODE);
// We can only one dimension that has -1
ASSERT(infer_dim == -1, ErrorCode::kUNSUPPORTED_NODE);
infer_dim = i;
}
}
return Status::success();
}
void get_kernel_params(::ONNX_NAMESPACE::NodeProto const& onnx_node,
nvinfer1::Dims* kernel_size,
nvinfer1::Dims* strides,
nvinfer1::Dims* beg_padding,
nvinfer1::Dims* end_padding,
nvinfer1::PaddingMode& paddingMode,
bool & count_exclude_padding,
nvinfer1::Dims* dilations,
nvinfer1::Dims* output_padding) {
const int nbSpatialDims = kernel_size->nbDims;
OnnxAttrs attrs(onnx_node);
if( attrs.count("kernel_shape") ) {
auto const* onnx_kernel_size = attrs.at("kernel_shape");
setAttr(kernel_size, onnx_kernel_size, nbSpatialDims, 1);
}
if( attrs.count("strides") ) {
auto const* onnx_strides = attrs.at("strides");
setAttr(strides, onnx_strides, nbSpatialDims, 1);
}
if( dilations && attrs.count("dilations") ) {
auto const* onnx_dilations = attrs.at("dilations");
setAttr(dilations, onnx_dilations, nbSpatialDims, 1);
}
if( attrs.count("count_include_pad")){
auto const* include_pad = attrs.at("count_include_pad");
int val = include_pad->i();
val == 1 ? count_exclude_padding=false : count_exclude_padding=true;
}
//For ConvTranspose Layer
if( attrs.count("output_padding") ) {
*output_padding = attrs.get<nvinfer1::Dims>("output_padding");
}
paddingMode = nvinfer1::PaddingMode::kEXPLICIT_ROUND_DOWN;
auto onnx_auto_pad = attrs.get("auto_pad", std::string("NOTSET"));
if( onnx_auto_pad == "VALID" || onnx_auto_pad == "NOTSET" ) {
if( attrs.count("pads") ) {
auto onnx_padding = attrs.get<std::vector<int>>("pads");
int ndim = onnx_padding.size() / 2;
for(int i = 0; i < nbSpatialDims; ++i){
if(i < ndim){
beg_padding->d[i] = onnx_padding.at(i);
end_padding->d[i] = onnx_padding.at(i + ndim);
} else {
beg_padding->d[i] = 0;
end_padding->d[i] = 0;
}
}
}
}
else
{
// If auto_pad is SAME_LOWER or SAME_UPPER, input padding should be calculated
// "pads" attribute should not be specified
assert(!attrs.count("pads"));
// Note: ONNX is always NCHW ordering
if( onnx_auto_pad == "SAME_LOWER" )
{
paddingMode = nvinfer1::PaddingMode::kSAME_LOWER;
}
else if( onnx_auto_pad == "SAME_UPPER" )
{
paddingMode = nvinfer1::PaddingMode::kSAME_UPPER;
}
else
{
throw std::invalid_argument("Unexpected auto_pad value: " +
onnx_auto_pad);
}
}
}
nvinfer1::ScaleMode get_scale_mode(nvinfer1::Dims const& weights_shape, nvinfer1::Dims const& tensor_shape)
{
if (weights_shape.nbDims == 1)
{
if (weights_shape.d[0] == 1)
{
return nvinfer1::ScaleMode::kUNIFORM;
}
// Check for channel wide scale - assume tensor shape is NCHW.
else if (weights_shape.d[0] == tensor_shape.d[1])
{
return nvinfer1::ScaleMode::kCHANNEL;
}
}
return nvinfer1::ScaleMode::kELEMENTWISE;
}
nvinfer1::Dims makeDims(int nbDims, int val)
{
nvinfer1::Dims dims;
dims.nbDims = nbDims;
std::fill_n(dims.d, nbDims, val);
return dims;
}
nvinfer1::ITensor& makeShapeTensor(IImporterContext* ctx, nvinfer1::Dims dims)
{
auto tempWeights = ctx->createTempWeights(::ONNX_NAMESPACE::TensorProto_DataType_INT32, makeDims(1, dims.nbDims));
for(int i = 0; i < dims.nbDims; i++)
{
static_cast<int32_t*>(tempWeights.values)[i] = dims.d[i];
}
auto valueWeights = TensorOrWeights{tempWeights};
return convertToTensor(valueWeights, ctx);
}
nvinfer1::ITensor* overwriteDim(IImporterContext* ctx, nvinfer1::ITensor* shape, nvinfer1::ITensor* dim, int axis)
{
const int shapeLength = shape->getDimensions().d[0];
std::vector<nvinfer1::ITensor*> dims{};
for (int i = 0; i < shapeLength; ++i)
{
if (i == axis)
{
dims.emplace_back(dim);
}
else
{
dims.emplace_back(gatherDimension(ctx, shape, i, nvinfer1::Dims{1, 1}));
}
}
return ctx->network()->addConcatenation(dims.data(), dims.size())->getOutput(0);
}