-
Notifications
You must be signed in to change notification settings - Fork 545
/
onnxOpImporters.cpp
7244 lines (6333 loc) · 315 KB
/
onnxOpImporters.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-License-Identifier: Apache-2.0
*/
#if defined(_MSC_VER)
#define _USE_MATH_DEFINES
#endif
#include <cmath>
#include "ConditionalHelpers.hpp"
#include "LoopHelpers.hpp"
#include "ModelImporter.hpp"
#include "NvInfer.h"
#include "NvInferPlugin.h"
#include "NvInferRuntime.h"
#include "OnnxAttrs.hpp"
#include "RNNHelpers.hpp"
#include "ShapeTensor.hpp"
#include "bfloat16.hpp"
#include "errorHelpers.hpp"
#include "half.h"
#include "importerUtils.hpp"
#include "onnxOpImporters.hpp"
#include <algorithm> // For std::min, std::max
#include <array>
#include <cstring> // For std::memcpy, std::memset
#include <iostream>
#include <iterator>
#include <numeric> // For std::iota
#include <sstream>
#include <tuple>
#include <unordered_set>
namespace onnx2trt
{
StringMap<NodeImporter>& getBuiltinOpImporterMap()
{
static StringMap<NodeImporter> builtin_op_importers;
return builtin_op_importers;
}
namespace
{
using nvinfer1::DataType;
#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) \
NodeOutputs import##op(ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, size_t const nodeIdx, \
std::vector<TensorOrWeights>& inputs)
#define DEFINE_BUILTIN_OP_IMPORTER(op) \
NodeOutputs import##op(ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, size_t const nodeIdx, \
std::vector<TensorOrWeights>& inputs); \
static bool const op##_registered_builtin_op = registerBuiltinOpImporter(#op, import##op); \
IGNORE_UNUSED_GLOBAL(op##_registered_builtin_op); \
NodeOutputs import##op(ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, size_t const nodeIdx, \
std::vector<TensorOrWeights>& inputs)
#define RETURN_FIRST_OUTPUT(layer, node, nodeIdx) \
do \
{ \
nvinfer1::ILayer* layer_ptr = layer; \
ONNXTRT_CHECK_NODE(layer_ptr, "Input layer is null.", node, nodeIdx, ErrorCode::kINVALID_NODE); \
auto* output = N_CHECK(layer->getOutput(0)); \
return {{output}}; \
} while (0)
#define RETURN_IDENTITY(input, node, nodeIdx) \
do \
{ \
TensorOrWeights output = identity(ctx, input); \
ONNXTRT_CHECK_NODE(output, "Failed to add an identity layer.", node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE); \
return {{output}}; \
} while (0)
#define RETURN_ALL_OUTPUTS(layer, node, nodeIdx) \
do \
{ \
nvinfer1::ILayer* layer_ptr = layer; \
ONNXTRT_CHECK_NODE(layer_ptr, "The input layer is null.", node, nodeIdx, ErrorCode::kINVALID_NODE); \
std::vector<TensorOrWeights> outputs; \
for (int i = 0; i < layer_ptr->getNbOutputs(); ++i) \
outputs.push_back(N_CHECK(layer_ptr->getOutput(i))); \
return {outputs}; \
} while (0)
void assertIsWeights(TensorOrWeights const& input, std::string const& specificMsg)
{
if (!input.is_weights())
{
std::ostringstream msg;
msg << specificMsg;
msg << " Try applying constant folding on the model using Polygraphy: "
"https://github.com/NVIDIA/TensorRT/tree/master/tools/Polygraphy/examples/cli/surgeon/"
"02_folding_constants";
throw std::runtime_error(msg.str());
}
}
bool registerBuiltinOpImporter(std::string op, NodeImporter const& importer)
{
bool inserted = getBuiltinOpImporterMap().insert({op, importer}).second;
assert(inserted);
return inserted;
}
bool onlySupportInt32TRTPlugin(std::string const& pluginName)
{
// TRT plugins that doesn't support INT64 as inputs, but support INT32.
static std::vector<std::string> const names = {
"CustomQKVToContextPluginDynamic",
"EfficientNMS_TRT",
"EfficientNMS_ONNX_TRT",
"EfficientNMS_Implicit_TF_TRT",
"EfficientNMS_Explicit_TF_TRT",
"VoxelGeneratorPlugin",
"ScatterND",
"ROIAlign_TRT",
"PillarScatterPlugin",
"MultiscaleDeformableAttnPlugin_TRT",
"CustomEmbLayerNormPluginDynamic",
};
return std::find(names.begin(), names.end(), pluginName) != names.end();
}
DEFINE_BUILTIN_OP_IMPORTER(Abs)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kABS);
}
DEFINE_BUILTIN_OP_IMPORTER(Acos)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kACOS);
}
DEFINE_BUILTIN_OP_IMPORTER(Acosh)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kACOSH);
}
DEFINE_BUILTIN_OP_IMPORTER(And)
{
return elementwiseHelper(ctx, node, nodeIdx, inputs, nvinfer1::ElementWiseOperation::kAND);
}
DEFINE_BUILTIN_OP_IMPORTER(Asin)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kASIN);
}
DEFINE_BUILTIN_OP_IMPORTER(Asinh)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kASINH);
}
DEFINE_BUILTIN_OP_IMPORTER(Atan)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kATAN);
}
DEFINE_BUILTIN_OP_IMPORTER(Atanh)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kATANH);
}
DEFINE_BUILTIN_OP_IMPORTER(Add)
{
return elementwiseHelper(ctx, node, nodeIdx, inputs, nvinfer1::ElementWiseOperation::kSUM);
}
DEFINE_BUILTIN_OP_IMPORTER(ArgMax)
{
return argMinMaxHelper(ctx, node, nodeIdx, inputs, nvinfer1::TopKOperation::kMAX);
}
DEFINE_BUILTIN_OP_IMPORTER(ArgMin)
{
return argMinMaxHelper(ctx, node, nodeIdx, inputs, nvinfer1::TopKOperation::kMIN);
}
DEFINE_BUILTIN_OP_IMPORTER(AveragePool)
{
return poolingHelper(ctx, node, nodeIdx, inputs, nvinfer1::PoolingType::kAVERAGE);
}
NodeOutputs batchnormFallback(
ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, size_t nodeIdx, std::vector<TensorOrWeights>& inputs)
{
using eOp = nvinfer1::ElementWiseOperation;
using uOp = nvinfer1::UnaryOperation;
nvinfer1::ITensor& input = convertToTensor(inputs.at(0), ctx);
int32_t const 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);
// Reshape batchnorm weights from [C] to [N, C, ...]
bool const needsExpandDims = rank > 1;
if (needsExpandDims)
{
std::vector<int32_t> 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);
auto varType = variance->getType();
nvinfer1::IConstantLayer* epsLayer;
if (varType == DataType::kHALF)
{
epsLayer = addConstantScalar(
ctx, static_cast<half_float::half>(eps), ::ONNX_NAMESPACE::TensorProto::FLOAT16, scalarShape);
}
else if (varType == DataType::kBF16)
{
epsLayer
= addConstantScalar(ctx, static_cast<BFloat16>(eps), ::ONNX_NAMESPACE::TensorProto::BFLOAT16, scalarShape);
}
else
{
epsLayer = addConstantScalar(ctx, eps, ::ONNX_NAMESPACE::TensorProto::FLOAT, scalarShape);
}
nvinfer1::ITensor* epsilon = N_CHECK(epsLayer->getOutput(0));
// batchnorm = scale * (input - mean) / sqrt(variance + epsilon) + bias
// The WAR is split the single c++ code line into 3 to avoid the sequence swap by compiler.
nvinfer1::ITensor* divisor
= getUnaryResult(ctx, *getElementWiseResult(ctx, *variance, *epsilon, eOp::kSUM), uOp::kSQRT);
nvinfer1::ITensor* dividend = getElementWiseResult(ctx, input, *mean, eOp::kSUB);
auto intermediateResult
= getElementWiseResult(ctx, *scale, *getElementWiseResult(ctx, *dividend, *divisor, eOp::kDIV), eOp::kPROD);
nvinfer1::IElementWiseLayer* layer = N_CHECK(ctx->network()->addElementWise(*intermediateResult, *bias, eOp::kSUM));
ctx->registerLayer(layer, node);
RETURN_FIRST_OUTPUT(layer, node, nodeIdx);
}
template <typename T>
NodeOutputs batchnormWeightHelper(
ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node, size_t nodeIdx, std::vector<TensorOrWeights>& inputs)
{
auto const scale = inputs.at(1).weights();
auto const bias = inputs.at(2).weights();
auto const mean = inputs.at(3).weights();
auto const variance = inputs.at(4).weights();
T const* scaleValues = static_cast<T*>(scale.values);
T const* biasValues = static_cast<T*>(bias.values);
T const* meanValues = static_cast<T*>(mean.values);
T const* varianceValues = static_cast<T*>(variance.values);
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
OnnxAttrs attrs(node, ctx);
T eps = static_cast<T>(attrs.get<float>("epsilon", 1e-5f));
// Fold the weights together into a single bias and scale
int32_t const nbChannels = scale.shape.d[0];
ShapedWeights::DataType weightType = typeid(T).hash_code() == typeid(BFloat16).hash_code()
? ::ONNX_NAMESPACE::TensorProto::BFLOAT16
: (typeid(T).hash_code() == typeid(half_float::half).hash_code() ? ::ONNX_NAMESPACE::TensorProto::FLOAT16
: ::ONNX_NAMESPACE::TensorProto::FLOAT);
auto combinedScale = ctx->createNamedTempWeights(weightType, scale.shape, /*batchNormNode=*/true);
auto combinedBias = ctx->createNamedTempWeights(weightType, bias.shape, /*batchNormNode=*/true);
// Validate that all the weights have the same amount of values
bool allSame = scale.count() == bias.count() && mean.count() == scale.count() && variance.count() == scale.count()
&& combinedScale.count() == scale.count() && combinedBias.count() == scale.count();
ONNXTRT_CHECK_NODE(
allSame, "Inputs to BatchNormalization must have the same shape!", node, nodeIdx, ErrorCode::kINVALID_NODE);
for (int32_t i = 0; i < nbChannels; ++i)
{
combinedScale.at<T>(i) = scaleValues[i] / sqrtf(varianceValues[i] + eps);
combinedBias.at<T>(i) = biasValues[i] - meanValues[i] * combinedScale.at<T>(i);
}
return scaleHelper(ctx, node, nodeIdx, *tensorPtr, nvinfer1::ScaleMode::kCHANNEL, combinedBias, combinedScale,
ShapedWeights::empty(weightType), combinedBias.getName(), combinedScale.getName());
}
DEFINE_BUILTIN_OP_IMPORTER(BatchNormalization)
{
ONNXTRT_CHECK_NODE((inputs.at(1).shape().nbDims == 1), "The shape of the scale input must be (C, )", node, nodeIdx,
ErrorCode::kINVALID_NODE);
ONNXTRT_CHECK_NODE((inputs.at(2).shape().nbDims == 1), "The shape of the bias input must be (C, )", node, nodeIdx,
ErrorCode::kINVALID_NODE);
ONNXTRT_CHECK_NODE((inputs.at(3).shape().nbDims == 1), "The shape of the mean input must be (C, )", node, nodeIdx,
ErrorCode::kINVALID_NODE);
ONNXTRT_CHECK_NODE((inputs.at(4).shape().nbDims == 1), "The shape of the var input must be (C, )", node, nodeIdx,
ErrorCode::kINVALID_NODE);
OnnxAttrs attrs(node, ctx);
bool const allInputsWeights = inputs.at(1).is_weights() && inputs.at(2).is_weights() && inputs.at(3).is_weights()
&& inputs.at(4).is_weights();
if (!allInputsWeights)
{
return batchnormFallback(ctx, node, nodeIdx, inputs);
}
auto tensorType = inputs.at(0).getType();
if (tensorType == inputs.at(1).getType() && tensorType == inputs.at(2).getType()
&& tensorType == inputs.at(3).getType() && tensorType == inputs.at(4).getType())
{
if (tensorType == "FLOAT")
{
return batchnormWeightHelper<float>(ctx, node, nodeIdx, inputs);
}
if (tensorType == "HALF")
{
return batchnormWeightHelper<half_float::half>(ctx, node, nodeIdx, inputs);
}
if (tensorType == "BF16")
{
return batchnormWeightHelper<BFloat16>(ctx, node, nodeIdx, inputs);
}
ONNXTRT_CHECK_NODE(false, "Invalid data type provided for BatchNormalization", node, nodeIdx,
ErrorCode::kUNSUPPORTED_NODE_DATATYPE);
}
auto const scale = inputs.at(1).weights();
auto const bias = inputs.at(2).weights();
auto const mean = inputs.at(3).weights();
auto const variance = inputs.at(4).weights();
// In the case of mixed precision, cast all values to FLOAT.
float const* scaleValues = ctx->getWeightsContext().getFP32Values(scale);
float const* biasValues = ctx->getWeightsContext().getFP32Values(bias);
float const* meanValues = ctx->getWeightsContext().getFP32Values(mean);
float const* varianceValues = ctx->getWeightsContext().getFP32Values(variance);
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
float eps = attrs.get<float>("epsilon", 1e-5f);
// Fold the weights together into a single bias and scale
int32_t const nbChannels = scale.shape.d[0];
auto combinedScale
= ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::FLOAT, scale.shape, /*batchNormNode=*/true);
auto combinedBias
= ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::FLOAT, bias.shape, /*batchNormNode=*/true);
// Validate that all the weights have the same amount of values
bool allSame = scale.count() == bias.count() && mean.count() == scale.count() && variance.count() == scale.count()
&& combinedScale.count() == scale.count() && combinedBias.count() == scale.count();
ONNXTRT_CHECK_NODE(
allSame, "Inputs to BatchNormalization must have the same shape!", node, nodeIdx, ErrorCode::kINVALID_NODE);
for (int32_t i = 0; i < nbChannels; ++i)
{
combinedScale.at<float>(i) = scaleValues[i] / sqrtf(varianceValues[i] + eps);
combinedBias.at<float>(i) = biasValues[i] - meanValues[i] * combinedScale.at<float>(i);
}
return scaleHelper(ctx, node, nodeIdx, *tensorPtr, nvinfer1::ScaleMode::kCHANNEL, combinedBias, combinedScale,
ShapedWeights::empty(::ONNX_NAMESPACE::TensorProto::FLOAT), combinedBias.getName(), combinedScale.getName());
}
DEFINE_BUILTIN_OP_IMPORTER(BlackmanWindow)
{
/***
Operation returns a window vector, where
Y[n] = 0.42 - 0.5cos(2pi*n / N) + 0.08cos(4pi*n / N)
Where N is the window length, and n is each element in the window.
Note that if `periodic == 0`, the denominator becomes N - 1.
This can be represented by creating a range 'n' from 0 -> N, and performing the operations elementwise.
***/
OnnxAttrs attrs(node, ctx);
int32_t outputDtype = attrs.get<int32_t>("output_datatype", 1);
int32_t periodic = attrs.get<int32_t>("periodic", 1);
ONNXTRT_CHECK_NODE(outputDtype == 1, "Output must be float32-type!", node, nodeIdx, ErrorCode::kINVALID_NODE);
constexpr float alpha = 0.42F;
constexpr float beta = 0.5F;
constexpr float gamma = 0.08F;
auto* N = &convertToTensor(inputs.at(0), ctx);
ONNXTRT_CHECK_NODE(
N->getDimensions().nbDims == 0, "Window length must be a scalar!", node, nodeIdx, ErrorCode::kINVALID_NODE);
auto* window = generateWindow(ctx, N);
auto lhsCosOutput = windowHelper(ctx, 2.F * M_PI, window, N, nvinfer1::UnaryOperation::kCOS, periodic);
auto betaTensor = N_CHECK(addConstantScalar(ctx, beta, ::ONNX_NAMESPACE::TensorProto_DataType_FLOAT,
nvinfer1::Dims{1, {1}})->getOutput(0));
auto betaLayer
= N_CHECK(ctx->network()->addElementWise(*betaTensor, *lhsCosOutput, nvinfer1::ElementWiseOperation::kPROD));
auto betaOutput = N_CHECK(betaLayer->getOutput(0));
auto rhsCosOutput = windowHelper(ctx, 4.F * M_PI, window, N, nvinfer1::UnaryOperation::kCOS, periodic);
auto gammaTensor = N_CHECK(addConstantScalar(ctx, gamma, ::ONNX_NAMESPACE::TensorProto_DataType_FLOAT,
nvinfer1::Dims{1, {1}})->getOutput(0));
auto gammaLayer
= N_CHECK(ctx->network()->addElementWise(*gammaTensor, *rhsCosOutput, nvinfer1::ElementWiseOperation::kPROD));
auto gammaOutput = N_CHECK(gammaLayer->getOutput(0));
auto alphaTensor = N_CHECK(addConstantScalar(ctx, alpha, ::ONNX_NAMESPACE::TensorProto_DataType_FLOAT,
nvinfer1::Dims{1, {1}})->getOutput(0));
auto alphaMinusBeta
= N_CHECK(ctx->network()->addElementWise(*alphaTensor, *betaOutput, nvinfer1::ElementWiseOperation::kSUB));
auto alphaMinusBetaTensor = N_CHECK(alphaMinusBeta->getOutput(0));
auto plusGamma = N_CHECK(
ctx->network()->addElementWise(*alphaMinusBetaTensor, *gammaOutput, nvinfer1::ElementWiseOperation::kSUM));
RETURN_FIRST_OUTPUT(plusGamma, node, nodeIdx);
}
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. Ignore "saturate" attribute as TRT will reject casts to FP8.
auto onnxType = attrs.get<int32_t>("to");
DataType newType{DataType::kFLOAT};
LOG_VERBOSE("Casting to type: " << newType);
ONNXTRT_CHECK_NODE(convertDtype(onnxType, &newType), "Unsupported cast!", node, nodeIdx, ErrorCode::kINVALID_NODE);
// Add the layer.
nvinfer1::ICastLayer* layer = N_CHECK(ctx->network()->addCast(tensor, newType));
ctx->registerLayer(layer, node);
RETURN_FIRST_OUTPUT(layer, node, nodeIdx);
}
DEFINE_BUILTIN_OP_IMPORTER(CastLike)
{
// Get input tensor to cast
nvinfer1::ITensor& tensor = convertToTensor(inputs.at(0), ctx);
// Get datatype to cast to, extracted from the second input tensor. Ignore "saturate" attribute as TRT will reject
// casts to FP8.
auto type = convertToTensor(inputs.at(1), ctx).getType();
nvinfer1::ICastLayer* layer = N_CHECK(ctx->network()->addCast(tensor, type));
ctx->registerLayer(layer, node);
RETURN_FIRST_OUTPUT(layer, node, nodeIdx);
}
DEFINE_BUILTIN_OP_IMPORTER(Ceil)
{
return unaryHelper(ctx, node, nodeIdx, inputs.at(0), nvinfer1::UnaryOperation::kCEIL);
}
DEFINE_BUILTIN_OP_IMPORTER(Celu)
{
using eOp = nvinfer1::ElementWiseOperation;
using uOp = nvinfer1::UnaryOperation;
using eOpInstuctor = std::tuple<int, int, const nvinfer1::ElementWiseOperation>;
ONNXTRT_CHECK_NODE((!inputs.empty()), "Inputs vector is empty.", node, nodeIdx, ErrorCode::kINVALID_NODE);
OnnxAttrs attrs(node, ctx);
TensorOrWeights input = inputs.at(0);
float alpha = attrs.get<float>("alpha", 1.0);
TensorOrWeights weightsOfZero = ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::FLOAT, {0, {}});
ShapedWeights weightsOfOnes = ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::FLOAT, {0, {}});
std::vector<float> ones{1};
std::memcpy(weightsOfOnes.values, ones.data(), weightsOfOnes.count() * sizeof(float));
ShapedWeights weightsOfAlpha = ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::FLOAT, {0, {}});
std::vector<float> alphas{alpha};
std::memcpy(weightsOfAlpha.values, alphas.data(), weightsOfAlpha.count() * sizeof(float));
// Variable name -> index in inputTensors
// x -> 0
// 0 -> 1
// 1 -> 2
// alpha -> 3
std::vector<TensorOrWeights> newInputs{input, weightsOfZero, weightsOfOnes, weightsOfAlpha};
std::vector<nvinfer1::ITensor*> inputTensors;
int32_t maxNbDims = -1;
for (auto i : newInputs)
{
maxNbDims = std::max(maxNbDims, i.shape().nbDims);
}
for (auto i : newInputs)
{
auto* tensor_ptr = &convertToTensor(i, ctx);
// Broadcast all input tensors to size of maxNbDims
broadcastTensor(ctx, tensor_ptr, maxNbDims);
ONNXTRT_CHECK_NODE(tensor_ptr->getDimensions().nbDims == maxNbDims, "Failed to broadcast tensors elementwise!",
node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
inputTensors.push_back(tensor_ptr);
}
// Calculate (x/alpha)
std::vector<TensorOrWeights> tempInputs{newInputs[0], newInputs[3]};
elementwiseCheck(tempInputs, eOp::kDIV, node, nodeIdx);
nvinfer1::ITensor* combined = inputTensors.at(0);
auto* divLayer = N_CHECK(ctx->network()->addElementWise(*combined, *inputTensors.at(3), eOp::kDIV));
ctx->registerLayer(divLayer, node);
combined = N_CHECK(divLayer->getOutput(0));
// Calculate exp(x/alpha) -> 4
nvinfer1::IUnaryLayer* uLayer = N_CHECK(ctx->network()->addUnary(*combined, uOp::kEXP));
ctx->registerLayer(uLayer, node);
combined = N_CHECK(uLayer->getOutput(0));
inputTensors.push_back(combined);
std::vector<eOpInstuctor> operations{
// max(0,x) -> 5
eOpInstuctor(0, 1, eOp::kMAX),
// (exp(x/alpha)-1)) -> 6
eOpInstuctor(4, 2, eOp::kSUB),
// alpha*(exp(x/alpha)-1) -> 7
eOpInstuctor(3, 6, eOp::kPROD),
// min(0,alpha*(exp(x/alpha)-1)) -> 8
eOpInstuctor(1, 7, eOp::kMIN),
// max(0,x) + min(0,alpha*(exp(x/alpha)-1)) -> 9
eOpInstuctor(5, 8, eOp::kSUM),
};
for (auto it : operations)
{
nvinfer1::ITensor* firstTensor = inputTensors.at(std::get<0>(it));
nvinfer1::ITensor* secondTensor = inputTensors.at(std::get<1>(it));
eOp const op = std::get<2>(it);
tempInputs = {firstTensor, secondTensor};
elementwiseCheck(tempInputs, op, node, nodeIdx);
ONNXTRT_CHECK_NODE((firstTensor->getDimensions().nbDims == secondTensor->getDimensions().nbDims),
"The rank of operands should be the same adding inputs. First tensor rank is "
<< firstTensor->getDimensions().nbDims << ", but second tensor rank is "
<< secondTensor->getDimensions().nbDims << ".",
node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
auto* layer = N_CHECK(ctx->network()->addElementWise(*firstTensor, *secondTensor, op));
ctx->registerLayer(layer, node);
inputTensors.push_back(N_CHECK(layer->getOutput(0)));
}
return {{inputTensors.back()}};
}
// Helper function to perform clip through elementwise operations
template <typename ScalarType>
NodeOutputs elementwiseClipHelper(ImporterContext* ctx, ::ONNX_NAMESPACE::NodeProto const& node,
std::vector<TensorOrWeights>& inputs, size_t numInputs, int32_t onnxType)
{
OnnxAttrs attrs(node, ctx);
auto* input = &convertToTensor(inputs.at(0), ctx);
nvinfer1::ITensor* alphaT{nullptr};
nvinfer1::ITensor* betaT{nullptr};
ScalarType alpha = std::numeric_limits<ScalarType>::lowest();
ScalarType beta = std::numeric_limits<ScalarType>::max();
if (numInputs == 1)
{
alphaT = N_CHECK(addConstantScalar(ctx, alpha, onnxType)->getOutput(0));
betaT = N_CHECK(addConstantScalar(ctx, beta, onnxType)->getOutput(0));
}
else if (numInputs == 2)
{
alphaT = &convertToTensor(inputs.at(1), ctx);
betaT = N_CHECK(addConstantScalar(ctx, beta, onnxType)->getOutput(0));
}
else if (numInputs == 3)
{
// "min" can be optional if "max" is specified. Check for this case here
if (!inputs.at(1).isNullTensor())
{
alphaT = &convertToTensor(inputs.at(1), ctx);
}
else
{
alphaT = N_CHECK(addConstantScalar(ctx, alpha, onnxType)->getOutput(0));
}
if (!inputs.at(2).isNullTensor())
{
betaT = &convertToTensor(inputs.at(2), ctx);
}
else
{
betaT = N_CHECK(addConstantScalar(ctx, beta, onnxType)->getOutput(0));
}
}
// Now that we have alphaT and betaT, do the elementwise calculation
using eOp = nvinfer1::ElementWiseOperation;
broadcastTensors(ctx, input, alphaT);
broadcastTensors(ctx, input, betaT);
auto* lowerClipLayer = N_CHECK(ctx->network()->addElementWise(*input, *alphaT, eOp::kMAX));
auto* lowerClip = N_CHECK(lowerClipLayer->getOutput(0));
auto* upperClipLayer = N_CHECK(ctx->network()->addElementWise(*lowerClip, *betaT, eOp::kMIN));
auto* upperClip = N_CHECK(upperClipLayer->getOutput(0));
return {{upperClip}};
}
DEFINE_BUILTIN_OP_IMPORTER(Clip)
{
checkNotInvalidType(inputs.at(0), {"UINT8"}, node, nodeIdx);
// For INT32 and multi-input clips, use elementwise operators instead.
size_t numInputs = inputs.size();
bool elementwiseClip = inputs.at(0).isInt32() || inputs.at(0).isInt64();
for (size_t i = 1; i < numInputs; i++)
{
elementwiseClip |= inputs.at(i).is_tensor();
}
if (elementwiseClip)
{
auto type = convertToTensor(inputs.at(0), ctx).getType();
ONNXTRT_CHECK_NODE((type == DataType::kFLOAT || type == DataType::kHALF || type == DataType::kBF16
|| type == DataType::kINT32 || type == DataType::kINT64),
"This version of TensorRT only supports floating-point, INT32, or INT64 inputs for Clip! The current input "
"type is "
+ getTrtDtypeName(type) + ".",
node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
if (type == DataType::kHALF)
{
return elementwiseClipHelper<half_float::half>(
ctx, node, inputs, numInputs, ::ONNX_NAMESPACE::TensorProto::FLOAT16);
}
if (type == DataType::kBF16)
{
return elementwiseClipHelper<BFloat16>(
ctx, node, inputs, numInputs, ::ONNX_NAMESPACE::TensorProto::BFLOAT16);
}
if (type == DataType::kFLOAT)
{
return elementwiseClipHelper<float>(ctx, node, inputs, numInputs, ::ONNX_NAMESPACE::TensorProto::FLOAT);
}
if (type == DataType::kINT64)
{
return elementwiseClipHelper<int64_t>(ctx, node, inputs, numInputs, ::ONNX_NAMESPACE::TensorProto::INT64);
}
return elementwiseClipHelper<int32_t>(ctx, node, inputs, numInputs, ::ONNX_NAMESPACE::TensorProto::INT32);
}
// Activation path only supports float/half initializers
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)
{
// Handle "min" node input.
if (numInputs == 2)
{
ONNXTRT_CHECK_NODE(inputs.at(1).is_weights(), "Clip min value must be an initializer!", node, nodeIdx,
ErrorCode::kINVALID_NODE);
auto min = inputs.at(1).weights();
alpha = getSingleValueAsFloat(min);
}
// 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).isNullTensor())
{
ONNXTRT_CHECK_NODE(inputs.at(1).is_weights(), "Clip min value must be an initializer!", node, nodeIdx,
ErrorCode::kINVALID_NODE);
auto min = inputs.at(1).weights();
alpha = getSingleValueAsFloat(min);
}
if (!inputs.at(2).isNullTensor())
{
ONNXTRT_CHECK_NODE(inputs.at(2).is_weights(), "Clip max value must be an initializer!", node, nodeIdx,
ErrorCode::kINVALID_NODE);
auto max = inputs.at(2).weights();
beta = getSingleValueAsFloat(max);
}
}
}
else
{
alpha = attrs.get("min", std::numeric_limits<float>::lowest());
beta = attrs.get("max", std::numeric_limits<float>::max());
}
return activationHelper(ctx, node, nodeIdx, inputs, nvinfer1::ActivationType::kCLIP, &alpha, &beta);
}
DEFINE_BUILTIN_OP_IMPORTER(Concat)
{
checkNotInvalidType(inputs.at(0), {"UINT8"}, node, nodeIdx);
std::vector<nvinfer1::ITensor*> tensors;
for (auto& input : inputs)
{
auto* tensorPtr = &convertToTensor(input, ctx);
tensors.push_back(tensorPtr);
}
OnnxAttrs attrs(node, ctx);
int32_t axis = attrs.get<int32_t>("axis");
int32_t nbDims = inputs.at(0).shape().nbDims;
convertAxis(axis, nbDims, node, nodeIdx);
auto* layer = N_CHECK(ctx->network()->addConcatenation(tensors.data(), tensors.size()));
ctx->registerLayer(layer, node);
layer->setAxis(axis);
RETURN_FIRST_OUTPUT(layer, node, nodeIdx);
}
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 = N_CHECK(ctx->network()->addConstant(weights.shape, weights));
ctx->network()->setWeightsName(weights, weights.getName());
RETURN_FIRST_OUTPUT(layer, node, nodeIdx);
}
if (ctx->getOpsetVersion() >= 12)
{
if (attrs.count("value_float"))
{
ShapedWeights convertedWeights = ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::FLOAT, {0, {}});
float value = attrs.get<float>("value_float");
std::memcpy(convertedWeights.values, &value, convertedWeights.count() * sizeof(float));
return {{convertedWeights}};
}
if (attrs.count("value_floats"))
{
std::vector<float> values = attrs.get<std::vector<float>>("value_floats");
int32_t valueSize = values.size();
ShapedWeights convertedWeights
= ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::FLOAT, {1, {valueSize}});
std::memcpy(convertedWeights.values, values.data(), convertedWeights.count() * sizeof(float));
return {{convertedWeights}};
}
if (attrs.count("value_int"))
{
ShapedWeights convertedWeights = ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::INT64, {0, {}});
int64_t value = attrs.get<int64_t>("value_int");
std::memcpy(convertedWeights.values, &value, convertedWeights.count() * sizeof(int64_t));
return {{convertedWeights}};
}
if (attrs.count("value_ints"))
{
std::vector<int64_t> values = attrs.get<std::vector<int64_t>>("value_ints");
int32_t valueSize = values.size();
ShapedWeights convertedWeights
= ctx->createNamedTempWeights(::ONNX_NAMESPACE::TensorProto::INT64, {1, {valueSize}});
std::memcpy(convertedWeights.values, values.data(), convertedWeights.count() * sizeof(int64_t));
return {{convertedWeights}};
}
}
attrs.get<ShapedWeights>("value");
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->createNamedTempWeights(::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, value, shape)}};
}
DEFINE_BUILTIN_OP_IMPORTER(Conv)
{
if (inputs.at(1).is_tensor() || (inputs.size() > 2 && inputs.at(2).is_tensor()))
{
// Handle dynamic weights convolution
return convMultiInput(ctx, node, nodeIdx, inputs);
}
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);
ONNXTRT_CHECK_NODE(dims.nbDims >= 0, "TensorRT could not compute output dimensions of Conv", node, nodeIdx,
ErrorCode::kUNSUPPORTED_NODE);
bool const needToExpandDims = (dims.nbDims == 3);
if (needToExpandDims)
{
// Expand spatial dims from 1D to 2D
std::vector<int32_t> axes{3};
tensorPtr = unsqueezeTensor(ctx, node, *tensorPtr, axes);
ONNXTRT_CHECK_NODE(tensorPtr, "Failed to unsqueeze tensor.", node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
dims = tensorPtr->getDimensions();
}
if (kernelWeights.shape.nbDims == 3)
{
kernelWeights.shape.nbDims = 4;
kernelWeights.shape.d[3] = 1;
}
int32_t const nbSpatialDims = dims.nbDims - 2;
// Check that the number of spatial dimensions and the kernel shape matches up.
ONNXTRT_CHECK_NODE((nbSpatialDims == kernelWeights.shape.nbDims - 2),
"The number of spatial dimensions and the kernel shape doesn't match up for the Conv operator. Number of "
"spatial dimensions = "
<< nbSpatialDims << ", number of kernel dimensions = " << kernelWeights.shape.nbDims << ".",
node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
nvinfer1::Weights biasWeights;
if (inputs.size() == 3)
{
assertIsWeights(inputs.at(2), "The bias tensor is required to be an initializer for the Conv operator.");
auto shapedBiasWeights = inputs.at(2).weights();
// Unsqueeze scalar weights to 1D
if (shapedBiasWeights.shape.nbDims == 0)
{
shapedBiasWeights.shape = {1, {1}};
}
ONNXTRT_CHECK_NODE((shapedBiasWeights.shape.nbDims == 1), "The bias tensor is required to be 1D.", node,
nodeIdx, ErrorCode::kINVALID_NODE);
ONNXTRT_CHECK_NODE((shapedBiasWeights.shape.d[0] == kernelWeights.shape.d[0]),
"The shape of the bias tensor misaligns with the weight tensor. Shape of bias weights = "
<< shapedBiasWeights.shape.d[0] << ", shape of kernel weights = " << kernelWeights.shape.d[0] << ".",
node, nodeIdx, ErrorCode::kINVALID_NODE);
biasWeights = shapedBiasWeights;
}
else
{
biasWeights = ShapedWeights::empty(kernelWeights.type);
}
nvinfer1::Dims kernelSize;
kernelSize.nbDims = nbSpatialDims;
for (int32_t 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 excludePadding;
getKernelParams(
ctx, node, &kernelSize, &strides, &begPadding, &endPadding, paddingMode, excludePadding, &dilations);
for (int32_t i = 1; i <= nbSpatialDims; ++i)
{
ONNXTRT_CHECK_NODE((kernelSize.d[nbSpatialDims - i] == kernelWeights.shape.d[kernelWeights.shape.nbDims - i]),
"The size of spatial dimension and the size of kernel shape are not equal for the Conv operator. "
"Size of spatial dimensions = "
<< kernelSize.d[nbSpatialDims - i]
<< ", size of kernel dimensions = " << kernelWeights.shape.d[kernelWeights.shape.nbDims - i] << ".",
node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
}
int32_t nchan = dims.d[1];
int32_t noutput = kernelWeights.shape.d[0];
nvinfer1::IConvolutionLayer* layer
= N_CHECK(ctx->network()->addConvolutionNd(*tensorPtr, noutput, kernelSize, kernelWeights, biasWeights));
layer->setStrideNd(strides);
layer->setPaddingMode(paddingMode);
layer->setPrePadding(begPadding);
layer->setPostPadding(endPadding);
layer->setDilationNd(dilations);
OnnxAttrs attrs(node, ctx);
int32_t ngroup = attrs.get("group", 1);
ONNXTRT_CHECK_NODE((nchan == -1 || kernelWeights.shape.d[1] * ngroup == nchan),
"Kernel weight dimension failed to broadcast to input.", node, nodeIdx, ErrorCode::kINVALID_NODE);
layer->setNbGroups(ngroup);
// Register layer name as well as kernel weights and bias weights (if any)
ctx->registerLayer(layer, node);
ctx->network()->setWeightsName(kernelWeights, inputs.at(1).weights().getName());
if (inputs.size() == 3)
{
ctx->network()->setWeightsName(biasWeights, inputs.at(2).weights().getName());
}
tensorPtr = N_CHECK(layer->getOutput(0));
dims = tensorPtr->getDimensions();
if (needToExpandDims)
{
// Un-expand spatial dims back to 1D
std::vector<int32_t> axes{3};
tensorPtr = squeezeTensor(ctx, node, *tensorPtr, axes);
ONNXTRT_CHECK_NODE(tensorPtr, "Failed to squeeze tensor.", node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
}
LOG_VERBOSE("Using kernel: " << kernelSize << ", strides: " << strides << ", prepadding: " << begPadding
<< ", postpadding: " << endPadding << ", dilations: " << dilations
<< ", numOutputs: " << noutput << ", nbGroups: " << ngroup);
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)
{
// Expand spatial dims from 1D to 2D, return true if reshaped activation
auto const NCWtoNCHW = [&ctx, &node](nvinfer1::ITensor*& tensor, nvinfer1::Dims& tensorShape) {
if (tensor && tensor->getDimensions().nbDims == 3)
{
std::vector<int32_t> const axes{3};
tensor = unsqueezeTensor(ctx, node, *tensor, axes);
tensorShape = tensor->getDimensions();
return true;
}
// for initializer, just change the shape by appending 1
if (tensorShape.nbDims == 3)
{
tensorShape.nbDims = 4;
tensorShape.d[3] = 1;
}
return false;
};
ONNXTRT_CHECK_NODE(
inputs.size() >= 2, "deconvolution require at least 2 inputs.", node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
nvinfer1::ITensor* tensorPtr = &convertToTensor(inputs.at(0), ctx);
auto inputType = tensorPtr->getType();
nvinfer1::ITensor* kernelTensorPtr = inputs.at(1).is_tensor() ? &convertToTensor(inputs.at(1), ctx) : nullptr;
nvinfer1::ITensor* biasTensorPtr
= inputs.size() > 2 && inputs.at(2).is_tensor() ? &convertToTensor(inputs.at(2), ctx) : nullptr;
nvinfer1::Dims dims = tensorPtr->getDimensions();
// Deconvolution input must be at least 3D and at most 5D.
ONNXTRT_CHECK_NODE(dims.nbDims >= 3 && dims.nbDims <= 5,
"Deconvolution input must be at least 3D and at most 5D! The current input is rank " << dims.nbDims << ".",
node, nodeIdx, ErrorCode::kUNSUPPORTED_NODE);
// Kernel weights have layout [C, M/group, k1, k2, (k3)]
auto kernelShape = inputs.at(1).shape();
bool needReshapeBack = NCWtoNCHW(tensorPtr, dims);
NCWtoNCHW(kernelTensorPtr, kernelShape);
int32_t const nbSpatialDims = dims.nbDims - 2;
// Check that the number of spatial dimensions and the kernel shape matches up.
ONNXTRT_CHECK_NODE((nbSpatialDims == kernelShape.nbDims - 2),
"The number of spatial dimensions and the kernel shape doesn't match up. Number of spatial dimensions = "
<< nbSpatialDims << ", number of kernel dimensions = " << kernelShape.nbDims << ".",
node, nodeIdx, 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 excludePadding = false;
int32_t ngroup = attrs.get("group", 1);
int32_t noutput = kernelShape.d[1] * ngroup; // Note: Weights order is CKRS
// Get static bias weights
nvinfer1::Weights staticBiasWeights;
if (inputs.size() > 2 && biasTensorPtr == nullptr)
{
auto shapedBiasWeights = inputs.at(2).weights();