-
Notifications
You must be signed in to change notification settings - Fork 1
/
builtin_op_importers.cpp
4379 lines (3812 loc) · 190 KB
/
builtin_op_importers.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) 2020, 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 "builtin_op_importers.hpp"
#include "ModelImporter.hpp"
#include "NvInferPlugin.h"
#include "OnnxAttrs.hpp"
#include "ShapeTensor.hpp"
#include "onnx2trt_utils.hpp"
#include "LoopHelpers.hpp"
#include "RNNHelpers.hpp"
#include <algorithm> // For std::min, std::max
#include <array>
#include <cmath>
#include <cstring> // For std::memcpy, std::memset
#include <iterator>
#include <numeric> // For std::iota
#include <tuple>
#include <unordered_set>
#include <iostream>
namespace onnx2trt
{
string_map<NodeImporter>& getBuiltinOpImporterMap()
{
static string_map<NodeImporter> builtin_op_importers;
return builtin_op_importers;
}
namespace
{
#define IGNORE_UNUSED_GLOBAL(x) \
static void _ignore_unused2_##x(); \
static void _ignore_unused1_##x() \
{ \
(void) _ignore_unused2_##x; \
(void) x; \
} \
static void _ignore_unused2_##x() \
{ \
(void) _ignore_unused1_##x; \
} \
struct SwallowSemicolon##x \
{ \
}
#define DECLARE_BUILTIN_OP_IMPORTER(op) \
NodeImportResult import##op( \
IImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, std::vector<TensorOrWeights>& inputs)
#define DEFINE_BUILTIN_OP_IMPORTER(op) \
NodeImportResult import##op( \
IImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, std::vector<TensorOrWeights>& inputs); \
static const bool op##_registered_builtin_op = registerBuiltinOpImporter(#op, import##op); \
IGNORE_UNUSED_GLOBAL(op##_registered_builtin_op); \
NodeImportResult import##op( \
IImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, std::vector<TensorOrWeights>& inputs)
#define RETURN_FIRST_OUTPUT(layer) \
do \
{ \
nvinfer1::ILayer* layer_ptr = layer; \
ASSERT(layer_ptr, ErrorCode::kUNSUPPORTED_NODE); \
return {{layer_ptr->getOutput(0)}}; \
} while (0)
#define RETURN_IDENTITY(input) \
do \
{ \
TensorOrWeights output = identity(ctx, input); \
ASSERT(output, ErrorCode::kUNSUPPORTED_NODE); \
return {{output}}; \
} while (0)
#define RETURN_ALL_OUTPUTS(layer) \
do \
{ \
nvinfer1::ILayer* layer_ptr = layer; \
ASSERT(layer_ptr, ErrorCode::kUNSUPPORTED_NODE); \
std::vector<TensorOrWeights> outputs; \
for (int i = 0; i < layer_ptr->getNbOutputs(); ++i) \
outputs.push_back(layer_ptr->getOutput(i)); \
return {outputs}; \
} while (0)
bool registerBuiltinOpImporter(std::string op, NodeImporter const& importer)
{
bool inserted = getBuiltinOpImporterMap().insert({op, importer}).second;
assert(inserted);
return inserted;
}
DEFINE_BUILTIN_OP_IMPORTER(Abs)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kABS);
}
DEFINE_BUILTIN_OP_IMPORTER(Acos)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kACOS);
}
DEFINE_BUILTIN_OP_IMPORTER(Acosh)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kACOSH);
}
DEFINE_BUILTIN_OP_IMPORTER(And)
{
return elementwiseHelper(ctx, node, inputs, nvinfer1::ElementWiseOperation::kAND);
}
DEFINE_BUILTIN_OP_IMPORTER(Asin)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kASIN);
}
DEFINE_BUILTIN_OP_IMPORTER(Asinh)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kASINH);
}
DEFINE_BUILTIN_OP_IMPORTER(Atan)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kATAN);
}
DEFINE_BUILTIN_OP_IMPORTER(Atanh)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kATANH);
}
DEFINE_BUILTIN_OP_IMPORTER(Add)
{
return elementwiseHelper(ctx, node, inputs, nvinfer1::ElementWiseOperation::kSUM);
}
DEFINE_BUILTIN_OP_IMPORTER(ArgMax)
{
return argMinMaxHelper(ctx, node, inputs, nvinfer1::TopKOperation::kMAX);
}
DEFINE_BUILTIN_OP_IMPORTER(ArgMin)
{
return argMinMaxHelper(ctx, node, inputs, nvinfer1::TopKOperation::kMIN);
}
DEFINE_BUILTIN_OP_IMPORTER(AveragePool)
{
return poolingHelper(ctx, node, inputs, nvinfer1::PoolingType::kAVERAGE);
}
NodeImportResult batchnormFallback(
IImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, std::vector<TensorOrWeights>& inputs)
{
using eOp = nvinfer1::ElementWiseOperation;
using uOp = nvinfer1::UnaryOperation;
nvinfer1::ITensor& input = convertToTensor(inputs.at(0), ctx);
const int rank = input.getDimensions().nbDims;
nvinfer1::ITensor* scale = &convertToTensor(inputs.at(1), ctx);
nvinfer1::ITensor* bias = &convertToTensor(inputs.at(2), ctx);
nvinfer1::ITensor* mean = &convertToTensor(inputs.at(3), ctx);
nvinfer1::ITensor* variance = &convertToTensor(inputs.at(4), ctx);
const bool hasCDimension = rank > 1;
if (hasCDimension)
{
std::vector<int> axes(rank - 1);
axes[0] = 0;
std::iota(axes.begin() + 1, axes.end(), 2);
scale = unsqueezeTensor(ctx, node, *scale, axes);
bias = unsqueezeTensor(ctx, node, *bias, axes);
mean = unsqueezeTensor(ctx, node, *mean, axes);
variance = unsqueezeTensor(ctx, node,*variance, axes);
}
OnnxAttrs attrs(node, ctx);
float eps = attrs.get<float>("epsilon", 1e-5f);
nvinfer1::Dims scalarShape{rank};
std::fill(scalarShape.d, scalarShape.d + scalarShape.nbDims, 1);
nvinfer1::ITensor* epsilon
= addConstantScalar(ctx, eps, ::ONNX_NAMESPACE::TensorProto::FLOAT, scalarShape)->getOutput(0);
// batchnorm = scale * (input - mean) / sqrt(variance + epsilon) + bias
nvinfer1::IElementWiseLayer* layer = ctx->network()->addElementWise(
*ctx->network()
->addElementWise(*scale,
*ctx->network()
->addElementWise(*ctx->network()->addElementWise(input, *mean, eOp::kSUB)->getOutput(0),
*ctx->network()
->addUnary(*ctx->network()->addElementWise(*variance, *epsilon, eOp::kSUM)->getOutput(0),
uOp::kSQRT)
->getOutput(0),
eOp::kDIV)
->getOutput(0),
eOp::kPROD)
->getOutput(0),
*bias, eOp::kSUM);
ctx->registerLayer(layer, node.name());
RETURN_FIRST_OUTPUT(layer);
}
DEFINE_BUILTIN_OP_IMPORTER(BatchNormalization)
{
// Scale, bias, mean, and variance must be initializers
auto scale_weights = inputs.at(1).weights();
auto bias_weights = inputs.at(2).weights();
auto mean_weights = inputs.at(3).weights();
auto variance_weights = inputs.at(4).weights();
const bool allInputsWeights = inputs.at(1).is_weights() && inputs.at(2).is_weights() && inputs.at(3).is_weights()
&& inputs.at(4).is_weights();
const bool allWeightsFloat = scale_weights.type == ::ONNX_NAMESPACE::TensorProto::FLOAT
&& bias_weights.type == ::ONNX_NAMESPACE::TensorProto::FLOAT
&& mean_weights.type == ::ONNX_NAMESPACE::TensorProto::FLOAT
&& variance_weights.type == ::ONNX_NAMESPACE::TensorProto::FLOAT;
const bool canFoldWeights = allInputsWeights && allWeightsFloat;
if (!canFoldWeights)
{
return batchnormFallback(ctx, node, inputs);
}
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
OnnxAttrs attrs(node, ctx);
float eps = attrs.get<float>("epsilon", 1e-5f);
nvinfer1::Dims dims = tensorPtr->getDimensions();
bool needToExpandDims = (dims.nbDims == 3);
if (needToExpandDims)
{
// Expand spatial dims from 1D to 2D
std::vector<int> axes{3};
tensorPtr = unsqueezeTensor(ctx, node, *tensorPtr, axes);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
dims = tensorPtr->getDimensions();
}
// Number of channels is equal to the length of scale_weights.
int nchan = scale_weights.shape.d[0];
nvinfer1::Dims weights_shape{1, {nchan}};
ASSERT(scale_weights.shape == weights_shape, ErrorCode::kINVALID_NODE);
ASSERT(bias_weights.shape == weights_shape, ErrorCode::kINVALID_NODE);
ASSERT(mean_weights.shape == weights_shape, ErrorCode::kINVALID_NODE);
ASSERT(variance_weights.shape == weights_shape, ErrorCode::kINVALID_NODE);
auto combined_scale_weights = ctx->createTempWeights(scale_weights.type, scale_weights.shape);
auto combined_bias_weights = ctx->createTempWeights(bias_weights.type, bias_weights.shape);
size_t nweight = nchan;
// Fold the weights together into a single bias and scale
for (size_t i = 0; i < nweight; ++i)
{
float scale = (static_cast<float const*>(scale_weights.values))[i];
float bias = (static_cast<float const*>(bias_weights.values))[i];
float mean = (static_cast<float const*>(mean_weights.values))[i];
float variance = (static_cast<float const*>(variance_weights.values))[i];
float& combined_scale_ref = const_cast<float*>(static_cast<float const*>(combined_scale_weights.values))[i];
float& combined_bias_ref = const_cast<float*>(static_cast<float const*>(combined_bias_weights.values))[i];
combined_scale_ref = scale / sqrtf(variance + eps);
combined_bias_ref = bias - mean * combined_scale_ref;
}
// If dimensions were not expanded return the output of the scale operation
if (!needToExpandDims)
{
return scaleHelper(
ctx, node, *tensorPtr, nvinfer1::ScaleMode::kCHANNEL, combined_bias_weights, combined_scale_weights, {}, bias_weights.getName(), scale_weights.getName());
}
else
{
auto scaledResult = scaleHelper(
ctx, node, *tensorPtr, nvinfer1::ScaleMode::kCHANNEL, combined_bias_weights, combined_scale_weights, {}, bias_weights.getName(), scale_weights.getName());
// Squeeze spatial dims back to 1D
tensorPtr = &convertToTensor(scaledResult.value().at(0), ctx);
std::vector<int> axes{3};
tensorPtr = squeezeTensor(ctx, node, *tensorPtr, axes);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
return {{tensorPtr}};
}
}
DEFINE_BUILTIN_OP_IMPORTER(Cast)
{
// Get input node.
nvinfer1::ITensor& tensor = convertToTensor(inputs.at(0), ctx);
OnnxAttrs attrs(node, ctx);
// Get data type to cast to.
nvinfer1::DataType dtype = tensor.getType();
auto onnxType = attrs.get<int32_t>("to");
ASSERT(convertDtype(onnxType, &dtype) && "Unsupported cast!", ErrorCode::kINVALID_NODE);
LOG_VERBOSE("Casting to type: " << dtype);
// Add the layer.
nvinfer1::IIdentityLayer* layer = ctx->network()->addIdentity(tensor);
layer->setOutputType(0, dtype);
ctx->registerLayer(layer, node.name());
RETURN_FIRST_OUTPUT(layer);
}
DEFINE_BUILTIN_OP_IMPORTER(Ceil)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kCEIL);
}
DEFINE_BUILTIN_OP_IMPORTER(Clip)
{
OnnxAttrs attrs(node, ctx);
// beta is the upper bound
float alpha = std::numeric_limits<float>::lowest();
float beta = std::numeric_limits<float>::max();
if (ctx->getOpsetVersion() >= 11)
{
int numInputs = inputs.size();
// Handle "min" node input.
if (numInputs == 2)
{
ASSERT(inputs.at(1).is_weights() && "Clip min value must be an initializer!", ErrorCode::kUNSUPPORTED_NODE);
auto min = inputs.at(1).weights();
alpha = static_cast<float*>(min.values)[0];
}
// Handle both "min" and "max" node inputs
else if (numInputs == 3)
{
// "min" can be optional if "max" is specified. Check for this case here
if (inputs.at(1))
{
ASSERT(inputs.at(1).is_weights() && "Clip min value must be an initializer!",
ErrorCode::kUNSUPPORTED_NODE);
auto min = inputs.at(1).weights();
alpha = static_cast<float*>(min.values)[0];
}
ASSERT(inputs.at(2).is_weights() && "Clip max value must be an initializer!", ErrorCode::kUNSUPPORTED_NODE);
auto max = inputs.at(2).weights();
beta = static_cast<float*>(max.values)[0];
}
}
else
{
alpha = attrs.get("min", std::numeric_limits<float>::lowest());
beta = attrs.get("max", std::numeric_limits<float>::max());
}
nvinfer1::ITensor* clipOut
= &activationHelper(ctx, node, inputs, nvinfer1::ActivationType::kCLIP, &alpha, &beta).value().at(0).tensor();
return {{clipOut}};
}
DEFINE_BUILTIN_OP_IMPORTER(Concat)
{
std::vector<nvinfer1::ITensor*> tensors;
for (auto& input : inputs)
{
// TRT does not support BOOL input types for this node
ASSERT(!input.isBool(), ErrorCode::kUNSUPPORTED_NODE);
tensors.push_back(&convertToTensor(input, ctx));
}
OnnxAttrs attrs(node, ctx);
int axis = attrs.get<int>("axis");
int nbDims = inputs.at(0).shape().nbDims;
TRT_CHECK(convertAxis(axis, nbDims));
auto* layer = ctx->network()->addConcatenation(tensors.data(), tensors.size());
ctx->registerLayer(layer, node.name());
ASSERT(layer, ErrorCode::kUNSUPPORTED_NODE);
layer->setAxis(axis);
RETURN_FIRST_OUTPUT(layer);
}
DEFINE_BUILTIN_OP_IMPORTER(Constant)
{
OnnxAttrs attrs(node, ctx);
// Having the trt_outputs_range_min attributes means it's from
// serialized iNetworkDefinition.
if (!attrs.get<std::vector<float>>("trt_outputs_range_min", {}).empty())
{
// just create a constant layer here for 1-1 mapping during network deserialization
auto weights = attrs.get<ShapedWeights>("value");
auto* layer = ctx->network()->addConstant(weights.shape, weights);
RETURN_FIRST_OUTPUT(layer);
}
return {{attrs.get<ShapedWeights>("value")}};
}
DEFINE_BUILTIN_OP_IMPORTER(ConstantOfShape)
{
OnnxAttrs attrs(node, ctx);
nvinfer1::ITensor* shape = &convertToTensor(inputs.at(0), ctx);
ShapedWeights zeroWeights
= ctx->createTempWeights(::ONNX_NAMESPACE::TensorProto_DataType_FLOAT, nvinfer1::Dims{1, 1});
static_cast<float*>(zeroWeights.values)[0] = 0.f;
auto valueWeights = TensorOrWeights{attrs.get("value", zeroWeights)};
nvinfer1::ITensor* value = &convertToTensor(valueWeights, ctx);
return {{constantOfShape(ctx, node, value, shape)}};
}
DEFINE_BUILTIN_OP_IMPORTER(Conv)
{
ASSERT(inputs.at(0).is_tensor(), ErrorCode::kUNSUPPORTED_NODE);
if (inputs.at(1).is_tensor())
{
ASSERT(ctx->network()->hasExplicitPrecision() && "TensorRT only supports multi-input conv for explicit precision QAT networks!", ErrorCode::kUNSUPPORTED_NODE);
if (inputs.size() == 3)
{
ASSERT(inputs.at(2).is_weights(), ErrorCode::kUNSUPPORTED_NODE);
}
// Handle Multiinput convolution
return convMultiInput(ctx, node, inputs);
}
// Convolution Weights must be an initializer
ASSERT(inputs.at(1).is_weights(), ErrorCode::kUNSUPPORTED_NODE);
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
auto kernelWeights = inputs.at(1).weights();
nvinfer1::Dims dims = tensorPtr->getDimensions();
LOG_VERBOSE("Convolution input dimensions: " << dims);
bool needToExpandDims = (dims.nbDims == 3);
if (needToExpandDims)
{
// Expand spatial dims from 1D to 2D
std::vector<int> axes{3};
tensorPtr = unsqueezeTensor(ctx, node, *tensorPtr, axes);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
dims = tensorPtr->getDimensions();
}
if (kernelWeights.shape.nbDims == 3)
{
kernelWeights.shape.nbDims = 4;
kernelWeights.shape.d[3] = 1;
}
const int nbSpatialDims = dims.nbDims - 2;
// Check that the number of spatial dimensions and the kernel shape matches up.
ASSERT(nbSpatialDims == kernelWeights.shape.nbDims - 2, ErrorCode::kUNSUPPORTED_NODE);
nvinfer1::Weights bias_weights;
if (inputs.size() == 3)
{
ASSERT(inputs.at(2).is_weights(), ErrorCode::kUNSUPPORTED_NODE);
auto shapedBiasWeights = inputs.at(2).weights();
ASSERT(shapedBiasWeights.shape.nbDims == 1, ErrorCode::kINVALID_NODE);
ASSERT(shapedBiasWeights.shape.d[0] == kernelWeights.shape.d[0], ErrorCode::kINVALID_NODE);
bias_weights = shapedBiasWeights;
}
else
{
bias_weights = ShapedWeights::empty(kernelWeights.type);
}
nvinfer1::Dims kernelSize;
kernelSize.nbDims = nbSpatialDims;
for (int i = 1; i <= nbSpatialDims; ++i)
{
kernelSize.d[nbSpatialDims - i] = kernelWeights.shape.d[kernelWeights.shape.nbDims - i];
}
nvinfer1::Dims strides = makeDims(nbSpatialDims, 1);
nvinfer1::Dims begPadding = makeDims(nbSpatialDims, 0);
nvinfer1::Dims endPadding = makeDims(nbSpatialDims, 0);
nvinfer1::Dims dilations = makeDims(nbSpatialDims, 1);
nvinfer1::PaddingMode paddingMode;
bool exclude_padding;
getKernelParams(
ctx, node, &kernelSize, &strides, &begPadding, &endPadding, paddingMode, exclude_padding, &dilations);
for (int i = 1; i <= nbSpatialDims; ++i)
{
ASSERT(kernelSize.d[nbSpatialDims - i] == kernelWeights.shape.d[kernelWeights.shape.nbDims - i],
ErrorCode::kUNSUPPORTED_NODE);
}
int nchan = dims.d[1];
int noutput = kernelWeights.shape.d[0];
nvinfer1::IConvolutionLayer* layer
= ctx->network()->addConvolutionNd(*tensorPtr, noutput, kernelSize, kernelWeights, bias_weights);
ASSERT(layer, ErrorCode::kUNSUPPORTED_NODE);
layer->setStrideNd(strides);
layer->setPaddingMode(paddingMode);
layer->setPrePadding(begPadding);
layer->setPostPadding(endPadding);
layer->setDilationNd(dilations);
OnnxAttrs attrs(node, ctx);
int ngroup = attrs.get("group", 1);
ASSERT(nchan == -1 || kernelWeights.shape.d[1] * ngroup == nchan, ErrorCode::kINVALID_NODE);
layer->setNbGroups(ngroup);
// Register layer name as well as kernel weights and bias weights (if any)
ctx->registerLayer(layer, getNodeName(node));
ctx->insertRefitMap(inputs.at(1).weights().getName(), getNodeName(node), nvinfer1::WeightsRole::kKERNEL);
if (inputs.size() == 3)
{
ctx->insertRefitMap(inputs.at(2).weights().getName(), getNodeName(node), nvinfer1::WeightsRole::kBIAS);
}
tensorPtr = layer->getOutput(0);
dims = tensorPtr->getDimensions();
if (needToExpandDims)
{
// Un-expand spatial dims back to 1D
std::vector<int> axes{3};
tensorPtr = squeezeTensor(ctx, node, *tensorPtr, axes);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
}
LOG_VERBOSE("Using kernel: " << kernelSize << ", strides: " << strides << ", prepadding: " << begPadding
<< ", postpadding: " << endPadding << ", dilations: " << dilations << ", numOutputs: " << noutput);
LOG_VERBOSE("Convolution output dimensions: " << dims);
return {{tensorPtr}};
}
// TRT only supports 2D or 3D deconvolutions (Layout: [N,C,D1,D2,(D3)])
// Inputs should be of dimension 4 or 5.
// When input.nbDims = 3, we expand it to 4D
DEFINE_BUILTIN_OP_IMPORTER(ConvTranspose)
{
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
nvinfer1::Dims dims = tensorPtr->getDimensions();
// Deconvolution input must be at least 3D and at most 5D.
ASSERT(dims.nbDims >= 3 && dims.nbDims <= 5 && "TensorRT only supports 1D, 2D or 3D deconvolutions!",
ErrorCode::kUNSUPPORTED_NODE);
// Deconvolution weights must be an initializer
ASSERT(inputs.at(1).is_weights(), ErrorCode::kUNSUPPORTED_NODE);
// Kernel weights have layout [C, M/group, k1, k2, (k3)]
auto kernelWeights = inputs.at(1).weights();
bool needToExpandDims = (dims.nbDims == 3);
if (needToExpandDims)
{
std::vector<int> axes{3};
tensorPtr = unsqueezeTensor(ctx, node, *tensorPtr, axes);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
dims = tensorPtr->getDimensions();
}
if (kernelWeights.shape.nbDims == 3)
{
kernelWeights.shape.nbDims = 4;
kernelWeights.shape.d[3] = 1;
}
const int nbSpatialDims = dims.nbDims - 2;
// Check that the number of spatial dimensions and the kernel shape matches up.
ASSERT(nbSpatialDims == kernelWeights.shape.nbDims - 2, ErrorCode::kUNSUPPORTED_NODE);
// Get all attributes
OnnxAttrs attrs(node, ctx);
nvinfer1::Dims outputShape;
nvinfer1::Dims outputPadding = makeDims(nbSpatialDims, 0);
nvinfer1::Dims kernelSize;
nvinfer1::Dims strides = makeDims(nbSpatialDims, 1);
nvinfer1::Dims begPadding = makeDims(nbSpatialDims, 0);
nvinfer1::Dims endPadding = makeDims(nbSpatialDims, 0);
nvinfer1::Dims dilations = makeDims(nbSpatialDims, 1);
nvinfer1::PaddingMode paddingMode;
bool exclude_padding = false;
int ngroup = attrs.get("group", 1);
int noutput = kernelWeights.shape.d[1] * ngroup; // Note: Weights order is CKRS
// Check for bias_weights
nvinfer1::Weights biasWeights;
if (inputs.size() == 3)
{
ASSERT(inputs.at(2).is_weights(), ErrorCode::kUNSUPPORTED_NODE);
auto shapedBiasWeights = inputs.at(2).weights();
// ONNX requires shapedBiasWeights to be 1D
ASSERT(shapedBiasWeights.shape.nbDims == 1, ErrorCode::kINVALID_NODE);
ASSERT(shapedBiasWeights.shape.d[0] == noutput, ErrorCode::kINVALID_NODE);
biasWeights = shapedBiasWeights;
}
else
{
biasWeights = ShapedWeights::empty(kernelWeights.type);
}
// Kernel shape either comes from the attributes or extracted from the kernel weights shape
kernelSize.nbDims = nbSpatialDims;
for (int i = 1; i <= nbSpatialDims; ++i)
{
kernelSize.d[nbSpatialDims - i] = kernelWeights.shape.d[kernelWeights.shape.nbDims - i];
}
getKernelParams(ctx, node, &kernelSize, &strides, &begPadding, &endPadding, paddingMode, exclude_padding,
&dilations, &outputPadding);
for (int i = 1; i <= nbSpatialDims; ++i)
{
ASSERT(kernelSize.d[nbSpatialDims - i] == kernelWeights.shape.d[kernelWeights.shape.nbDims - i],
ErrorCode::kUNSUPPORTED_NODE);
}
// Set padding. ONNX ConvTranspose supports many different padding modes. Order of priority for padding:
// 1. Output shape is specified - calculate expected pre and post padding.
// 2. AUTO_PAD != NOTSET: ignore all other padding values and set padding mode with layer->setPaddingMode.
// Pad the resulting output vector with values from output_padding
// 3. Use specified "pads" values from the node. Pad the resulting output vector with values from output_padding
auto autoPadMode = attrs.get("auto_pad", std::string("NOTSET"));
if (attrs.count("output_shape") && autoPadMode == std::string("NOTSET"))
{
outputShape = attrs.get<nvinfer1::Dims>("output_shape");
// This function takes references to begPadding, endPadding and outputPadding and will update them with correct values
generatePadding(dims, outputShape, kernelSize, strides, dilations, nbSpatialDims, begPadding, endPadding,
outputPadding, paddingMode);
// NOTE: it is possible for generatePadding to produce negative values for pre and post padding, which usually happens when
// output_shape is provided but output_padding is not. Any negative values generated for post-padding can be translated
// into outputPadding to pad the output tensor post deconvolution. Any negative values for pre-padding are unsupported.
for (int i = 0; i < nbSpatialDims; i++)
{
ASSERT(begPadding.d[i] >= 0 && "TensorRT does not support negative pre-padding in the ConvTranspose operator!",
ErrorCode::kUNSUPPORTED_NODE);
// Update outputPadding with any negative values in endPadding, and set the corresponding value to 0.
if (endPadding.d[i] < 0)
{
outputPadding.d[i] = endPadding.d[i] * -1;
endPadding.d[i] = 0;
}
}
}
// When there is output_padding, if postPadding is larger than outputPadding, just adjust postPadding
// Or reduce outputPadding as minimum as possible.
bool hasOutputPadding = false;
if (outputPadding != makeDims(nbSpatialDims, 0) && autoPadMode == std::string("NOTSET"))
{
for (int i = 0; i < nbSpatialDims; ++i)
{
if (endPadding.d[i] - outputPadding.d[i] >= 0)
{
endPadding.d[i] -= outputPadding.d[i];
outputPadding.d[i] = 0;
}
else
{
// Reduce outputPadding as possible.
outputPadding.d[i] -= endPadding.d[i];
endPadding.d[i] = 0;
hasOutputPadding = true;
}
}
}
nvinfer1::Weights emptyBiasWeights = ShapedWeights::empty(kernelWeights.type);
// Create a deconvolution layer and set known attributes - strides,ngroups, and dilations
// If there is still output padding, remove the bias weights. Bias will be added below.
auto* layer = ctx->network()->addDeconvolutionNd(
*tensorPtr, noutput, kernelSize, kernelWeights, hasOutputPadding ? emptyBiasWeights : biasWeights);
layer->setStrideNd(strides);
layer->setNbGroups(ngroup);
layer->setDilationNd(dilations);
// Check that 3D deconvolution paddings is valid
if (nbSpatialDims == 3)
{
ASSERT(begPadding == endPadding && "TensorRT does not support asymmetrical padding for 3D deconvolutions!",
ErrorCode::kUNSUPPORTED_NODE);
}
layer->setPaddingMode(paddingMode);
layer->setPrePadding(begPadding);
layer->setPostPadding(endPadding);
LOG_VERBOSE("Running deconvolution with: " << "\n"
<< "Padding mode: " << autoPadMode << "\n"
<< "Pre-padding: " << begPadding << "\n"
<< "Post-padding: " << endPadding);
// Register layer, along with refittable kernel weights and bias weights (if any)
ctx->registerLayer(layer, getNodeName(node));
ctx->insertRefitMap(inputs.at(1).weights().getName(), getNodeName(node), nvinfer1::WeightsRole::kKERNEL);
if (inputs.size() == 3)
{
ctx->insertRefitMap(inputs.at(2).weights().getName(), getNodeName(node), nvinfer1::WeightsRole::kBIAS);
}
tensorPtr = layer->getOutput(0);
dims = tensorPtr->getDimensions();
// There is still output padding. Add a padding layer to handle it.
if (hasOutputPadding)
{
// TRT only support 2D padding on the outermost dimensions
ASSERT(outputPadding.nbDims == 2 || (outputPadding.nbDims == 3 && outputPadding.d[0] == 0),
ErrorCode::kUNSUPPORTED_NODE);
// Convert 3D padding to 2d padding
if (nbSpatialDims == 3)
{
outputPadding = {2, {outputPadding.d[1], outputPadding.d[2]}};
}
LOG_VERBOSE("Padding output deconvolution tensor with: " << outputPadding);
tensorPtr = ctx->network()->addPaddingNd(*tensorPtr, makeDims(2, 0), outputPadding)->getOutput(0);
// This bias is not handled by deconv. Use an elementwise to handle it.
if (biasWeights.count != 0)
{
// Set C dimension to weights count and set other dimensions to 1 to enable broadcast
auto constantDims = makeDims(dims.nbDims, 1);
constantDims.d[dims.nbDims - nbSpatialDims - 1] = biasWeights.count;
auto biasConstant = ctx->network()->addConstant(constantDims, biasWeights);
tensorPtr
= ctx->network()
->addElementWise(*tensorPtr, *biasConstant->getOutput(0), nvinfer1::ElementWiseOperation::kSUM)
->getOutput(0);
}
}
if (needToExpandDims)
{
std::vector<int> axes{3};
tensorPtr = squeezeTensor(ctx, node, *tensorPtr, axes);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
}
return {{tensorPtr}};
}
DEFINE_BUILTIN_OP_IMPORTER(Cos)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kCOS);
}
DEFINE_BUILTIN_OP_IMPORTER(Cosh)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kCOSH);
}
DEFINE_BUILTIN_OP_IMPORTER(DepthToSpace)
{
// Input tensor is in NCHW format
ASSERT(inputs.at(0).shape().nbDims == 4, ErrorCode::kUNSUPPORTED_NODE);
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
// TRT does not support BOOL input types for this node
ASSERT(tensorPtr->getType() != nvinfer1::DataType::kBOOL, ErrorCode::kUNSUPPORTED_NODE);
// Extract attributes
OnnxAttrs attrs(node, ctx);
auto blockSize = attrs.get<int>("blocksize");
auto mode = attrs.get<std::string>("mode", "DCR");
// Useful constants
const auto inputShape = shapeOf(*tensorPtr);
const auto N = gather(ctx, inputShape, shapeVector(0));
const auto C = gather(ctx, inputShape, shapeVector(1));
const auto H = gather(ctx, inputShape, shapeVector(2));
const auto W = gather(ctx, inputShape, shapeVector(3));
const auto blockSizeTensor = shapeVector(blockSize);
const auto C_2 = floorDiv(ctx, C, mul(ctx, blockSizeTensor, blockSizeTensor));
const auto H_2 = mul(ctx, H, blockSizeTensor);
const auto W_2 = mul(ctx, W, blockSizeTensor);
const int DCRPerm[6] = {0, 3, 4, 1, 5, 2};
const int CRDPerm[6] = {0, 1, 4, 2, 5, 3};
ShapeTensor firstShape;
nvinfer1::Permutation perm{};
if (mode == "DCR")
{
// First reshape to {N, blockSize, blockSize, C / (blockSize * blockSize), H, W}
firstShape = concat(ctx, N,
concat(ctx, blockSizeTensor,
concat(ctx, blockSizeTensor,
concat(ctx, C_2,
concat(ctx, H, W)))));
std::copy(std::begin(DCRPerm), std::end(DCRPerm), std::begin(perm.order));
}
else
{
// First reshape to {N, C / (blockSize * blockSize), blockSize, blockSize, H, W}
firstShape = concat(ctx, N,
concat(ctx, C_2,
concat(ctx, blockSizeTensor,
concat(ctx, blockSizeTensor,
concat(ctx, H, W)))));
std::copy(std::begin(CRDPerm), std::end(CRDPerm), std::begin(perm.order));
}
auto* firstShuffle = addShuffle(ctx, *tensorPtr, firstShape);
firstShuffle->setSecondTranspose(perm);
ctx->registerLayer(firstShuffle, node.name());
tensorPtr = firstShuffle->getOutput(0);
// Finally reshape to {N, C / (blockSize * blockSize), H * blockSize, W * blockSize};
auto secondShape = concat(ctx, N, concat(ctx, C_2, concat(ctx, H_2, W_2)));
auto* secondShuffle = addShuffle(ctx, *tensorPtr, secondShape);
tensorPtr = secondShuffle->getOutput(0);
return {{tensorPtr}};
}
DEFINE_BUILTIN_OP_IMPORTER(DequantizeLinear)
{
ASSERT(inputs.size() == 3, nvonnxparser::ErrorCode::kINVALID_NODE);
std::string name = node.name();
// Input 0 can be a weights or a tensor
nvinfer1::ITensor& input = convertToTensor(inputs.at(0), ctx);
std::string input_tensor_name = name + std::string("_input_weight_tensor");
input.setName(input_tensor_name.c_str());
// Second and third input should be a constant
ASSERT(inputs.at(1).is_weights(), nvonnxparser::ErrorCode::kINVALID_NODE);
ASSERT(inputs.at(2).is_weights(), nvonnxparser::ErrorCode::kINVALID_NODE);
auto type = inputs.at(1).weights().type;
auto scale = inputs.at(1).weights();
auto power = ShapedWeights::empty(type);
auto shift = createZeroShifts(inputs.at(2).weights(), type, ctx);
ASSERT(scale.count() == shift.count(), nvonnxparser::ErrorCode::kINVALID_NODE);
// Set Uniform scale mode by default.
nvinfer1::ScaleMode mode = nvinfer1::ScaleMode::kUNIFORM;
if (scale.count() != 1)
{
// Ensure that number of scales are equalt to output channel.
size_t K = input.getDimensions().d[0];
ASSERT(K == scale.count(), nvonnxparser::ErrorCode::kINVALID_NODE);
mode = nvinfer1::ScaleMode::kCHANNEL;
}
auto invScale = ctx->createTempWeights(scale.type, scale.shape);
auto invShift = ctx->createTempWeights(shift.type, shift.shape);
float* s = static_cast<float*>(scale.values);
float* ns = static_cast<float*>(invScale.values);
float* b = static_cast<float*>(shift.values);
float* nb = static_cast<float*>(invShift.values);
for (int i = 0, n = scale.count(); i < n; i++)
{
ns[i] = 1.0f / s[i];
nb[i] = -b[i] * ns[i];
}
// Map Quantization node to a scale node
auto layer = ctx->network()->addScale(input, mode, invShift, invScale, power);
// Set output precision type of the scale node to INT8 - indicates its a quantizing scale node.
layer->setOutputType(0, nvinfer1::DataType::kFLOAT);
std::string dequantize_node_name = name + std::string("_dequantize_scale_node");
std::string dequantize_node_output = dequantize_node_name + "_output_tensor";
layer->setName(dequantize_node_name.c_str());
layer->getOutput(0)->setName(dequantize_node_output.c_str());
// Return layer output
RETURN_FIRST_OUTPUT(layer);
}
DECLARE_BUILTIN_OP_IMPORTER(Mul);
DEFINE_BUILTIN_OP_IMPORTER(Div)
{
return elementwiseHelper(ctx, node, inputs, nvinfer1::ElementWiseOperation::kDIV);
}
DEFINE_BUILTIN_OP_IMPORTER(Dropout)
{
int noutputs = node.output().size();
if (noutputs == 1)
{
RETURN_IDENTITY(inputs.at(0));
}
else
{
// Error if opset version >= 10 as boolean not supported right now
ASSERT(ctx->getOpsetVersion() < 10, ErrorCode::kUNSUPPORTED_NODE);
// Add identity layer twice for both Dropout outputs: (output + mask)
std::vector<TensorOrWeights> outputs;
outputs.push_back(identity(ctx, inputs.at(0)));
outputs.push_back(identity(ctx, inputs.at(0)));
return outputs;
}
}
DEFINE_BUILTIN_OP_IMPORTER(Elu)
{
OnnxAttrs attrs(node, ctx);
float alpha = attrs.get<float>("alpha", 1.f);
return activationHelper(ctx, node, inputs, nvinfer1::ActivationType::kELU, &alpha);
}
DEFINE_BUILTIN_OP_IMPORTER(Equal)
{
return elementwiseHelper(ctx, node, inputs, nvinfer1::ElementWiseOperation::kEQUAL);
}
DEFINE_BUILTIN_OP_IMPORTER(Erf)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kERF);
}
DEFINE_BUILTIN_OP_IMPORTER(Exp)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kEXP);
}
DEFINE_BUILTIN_OP_IMPORTER(Expand)
{
// "Broadcast the input tensor following the given shape and the broadcast rule."
nvinfer1::ITensor& inputTensor = convertToTensor(inputs.at(0), ctx);
// TRT does not support BOOL input types for this node
ASSERT (inputTensor.getType() != nvinfer1::DataType::kBOOL, ErrorCode::kUNSUPPORTED_NODE);
const auto inputDims = shapeOf(inputTensor);
const auto inputRank = shapeOf(inputDims);
// "A 1-D tensor indicates the shape you want to expand to, following the broadcast rule"
ASSERT(inputs.at(1).shape().nbDims == 1, ErrorCode::kINVALID_VALUE);
ShapeTensor shape{inputs.at(1)};
const auto shapeLength = shapeOf(shape);
const ShapeTensor newRank = max(ctx, shapeLength, inputRank);
// "Dimensions are right alignment;..."
const ShapeTensor newDims = concat(ctx, fillShapeVector(ctx, 1, sub(ctx, newRank, inputRank)), inputDims);
nvinfer1::ITensor& newInputTensor = reshape(ctx, inputTensor, newDims);
// ", or the shape.ndim < input.shape.ndim"
ShapeTensor newShape = concat(ctx, fillShapeVector(ctx, 1, sub(ctx, newRank, shapeLength)), shape);
const ShapeTensor starts = similar(ctx, newDims, 0);
// Do the broadcast rule.
const ShapeTensor sizes = broadcast(ctx, newDims, newShape);
// Compute (x > 1 ? 1 : 0) for x in newDims, assuming positive x, using only TensorRT operations.
const ShapeTensor one = shapeVector(1);
const ShapeTensor strides = min(ctx, one, sub(ctx, newDims, one));
nvinfer1::ISliceLayer* sliceLayer = addSlice(ctx, newInputTensor, starts, sizes, strides);
ctx->registerLayer(sliceLayer, node.name());
RETURN_FIRST_OUTPUT(sliceLayer);
}
DEFINE_BUILTIN_OP_IMPORTER(Flatten)
{
OnnxAttrs attrs(node, ctx);
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
int nbDims = tensorPtr->getDimensions().nbDims;
int axis = attrs.get("axis", 1);
TRT_CHECK(convertAxis(axis, nbDims));
if (nbDims > 2)
{
tensorPtr = flattenTensor(ctx, node, *tensorPtr, axis, true);
ASSERT(tensorPtr, ErrorCode::kUNSUPPORTED_NODE);
}
return {{tensorPtr}};
}
DEFINE_BUILTIN_OP_IMPORTER(Floor)
{
return unaryHelper(ctx, node, inputs.at(0), nvinfer1::UnaryOperation::kFLOOR);
}
DEFINE_BUILTIN_OP_IMPORTER(Gather)
{
nvinfer1::ITensor& data = convertToTensor(inputs.at(0), ctx);
// TRT does not support BOOL input types for this node
ASSERT(data.getType() != nvinfer1::DataType::kBOOL, ErrorCode::kUNSUPPORTED_NODE);
nvinfer1::ITensor& indices = convertToTensor(inputs.at(1), ctx);
OnnxAttrs attrs(node, ctx);
int axis = attrs.get<int>("axis", 0);
int nbDims = inputs.at(0).shape().nbDims;
TRT_CHECK(convertAxis(axis, nbDims));
LOG_VERBOSE("Using Gather axis: " << axis);
auto* layer = ctx->network()->addGather(data, indices, axis);
ctx->registerLayer(layer, node.name());