/
defs.cc
3774 lines (3491 loc) · 136 KB
/
defs.cc
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
*/
#include "onnx/defs/data_propagators.h"
#include "onnx/defs/tensor/utils.h"
#include "onnx/defs/function.h"
#include "onnx/defs/tensor_proto_util.h"
#include <algorithm>
#include <cmath>
#include <numeric>
namespace ONNX_NAMESPACE {
static const char* Cast_ver13_doc = R"DOC(
The operator casts the elements of a given input tensor to a data type
specified by the 'to' argument and returns an output tensor of the same size in
the converted type. The 'to' argument must be one of the data types specified
in the 'DataType' enum field in the TensorProto message.
Casting from string tensor in plain (e.g., "3.14" and "1000") and scientific numeric representations
(e.g., "1e-5" and "1E8") to float types is supported. For example, converting string "100.5" to an integer may
result 100. There are some string literals reserved for special floating-point values;
"+INF" (and "INF"), "-INF", and "NaN" are positive infinity, negative infinity, and not-a-number, respectively.
Any string which can exactly match "+INF" in a case-insensitive way would be mapped to positive infinite. Similarly,
this case-insensitive rule is applied to "INF" and "NaN". When casting from numeric tensors
to string tensors, plain floating-point representation (such as "314.15926") would be used.
Converting non-numerical-literal string such as "Hello World!" is an undefined behavior. Cases
of converting string representing floating-point arithmetic value, such as "2.718", to INT is an undefined behavior.
Conversion from a numerical type to any numerical type is always allowed.
User must be aware of precision loss and value change caused by range difference between two types.
For example, a 64-bit float 3.1415926459 may be round to a 32-bit float 3.141592. Similarly, converting
an integer 36 to Boolean may produce 1 because we truncate bits which can't be stored in the targeted type.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Cast,
13,
OpSchema()
.SetDoc(Cast_ver13_doc)
.Attr(
"to",
"The data type to which the elements of the input tensor are cast. "
"Strictly must be one of the types from DataType enum in TensorProto",
AttributeProto::INT)
.Input(
0,
"input",
"Input tensor to be cast.",
"T1",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.Output(
0,
"output",
"Output tensor with the same shape as input with type "
"specified by the 'to' argument",
"T2",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.TypeConstraint(
"T1",
{"tensor(float16)",
"tensor(float)",
"tensor(double)",
"tensor(int8)",
"tensor(int16)",
"tensor(int32)",
"tensor(int64)",
"tensor(uint8)",
"tensor(uint16)",
"tensor(uint32)",
"tensor(uint64)",
"tensor(bool)",
"tensor(string)",
"tensor(bfloat16)"},
"Constrain input types. Casting from complex is not supported.")
.TypeConstraint(
"T2",
{"tensor(float16)",
"tensor(float)",
"tensor(double)",
"tensor(int8)",
"tensor(int16)",
"tensor(int32)",
"tensor(int64)",
"tensor(uint8)",
"tensor(uint16)",
"tensor(uint32)",
"tensor(uint64)",
"tensor(bool)",
"tensor(string)",
"tensor(bfloat16)"},
"Constrain output types. Casting to complex is not supported.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
propagateElemTypeFromAttributeToOutput(ctx, "to", 0);
if (hasNInputShapes(ctx, 1)) {
propagateShapeFromInputToOutput(ctx, 0, 0);
}
})
.PartialDataPropagationFunction([](DataPropagationContext& ctx) {
PropagateShapeDataFromInputToOutput(ctx, 0);
}));
static const char* CastLike_ver15_doc = R"DOC(
The operator casts the elements of a given input tensor (the first input) to
the same data type as the elements of the second input tensor.
See documentation of the Cast operator for further details.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
CastLike,
15,
OpSchema()
.SetDoc(CastLike_ver15_doc)
.Input(
0,
"input",
"Input tensor to be cast.",
"T1",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.Input(
1,
"target_type",
"The (first) input tensor will be cast to produce a tensor of the same type as this (second input) tensor.",
"T2",
OpSchema::Single,
true,
1,
OpSchema::NonDifferentiable)
.Output(
0,
"output",
"Output tensor produced by casting the first input tensor to have the same type as the second input tensor.",
"T2",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.TypeConstraint(
"T1",
{ "tensor(float16)",
"tensor(float)",
"tensor(double)",
"tensor(int8)",
"tensor(int16)",
"tensor(int32)",
"tensor(int64)",
"tensor(uint8)",
"tensor(uint16)",
"tensor(uint32)",
"tensor(uint64)",
"tensor(bool)",
"tensor(string)",
"tensor(bfloat16)" },
"Constrain input types. Casting from complex is not supported.")
.TypeConstraint(
"T2",
{ "tensor(float16)",
"tensor(float)",
"tensor(double)",
"tensor(int8)",
"tensor(int16)",
"tensor(int32)",
"tensor(int64)",
"tensor(uint8)",
"tensor(uint16)",
"tensor(uint32)",
"tensor(uint64)",
"tensor(bool)",
"tensor(string)",
"tensor(bfloat16)" },
"Constrain output types. Casting to complex is not supported.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
propagateElemTypeFromInputToOutput(ctx, 1, 0);
if (hasNInputShapes(ctx, 1)) {
propagateShapeFromInputToOutput(ctx, 0, 0);
}
})
.SetContextDependentFunctionBodyBuilder(
[](const FunctionBodyBuildContext& ctx,
const OpSchema& schema,
FunctionProto& functionProto) -> bool {
auto target_type = ctx.getInputType(1);
if ((target_type == nullptr) || (!target_type->has_tensor_type())) {
// we cannot create a correct function body without knowing the target element type
return false;
}
auto target_elt_type = target_type->tensor_type().elem_type();
std::vector<FunctionBodyHelper::NodeDef> body{
// nodes: {outputs, op, inputs, attributes}
{ {"output"}, "Cast", {"input"}, {MakeAttribute("to", (int64_t)(target_elt_type))} }
};
return FunctionBodyHelper::BuildFunctionProto(functionProto, schema, body, {});
}));
static const char* Reshape_ver14_doc = R"DOC(
Reshape the input tensor similar to numpy.reshape.
First input is the data tensor, second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor.
At most one dimension of the new shape can be -1. In this case, the value is
inferred from the size of the tensor and the remaining dimensions. A dimension
could also be 0, in which case the actual dimension value is unchanged (i.e. taken
from the input tensor). If 'allowzero' is set, and the new shape includes 0, the
dimension will be set explicitly to zero (i.e. not taken from input tensor))DOC";
ONNX_OPERATOR_SET_SCHEMA(
Reshape,
14,
OpSchema()
.SetDoc(Reshape_ver14_doc)
.Attr(
"allowzero",
"(Optional) By default, when any value in the 'shape' input is equal to zero "
"the corresponding dimension value is copied from the input tensor dynamically. "
"allowzero=1 indicates that if any value in the 'shape' input is set to zero, "
"the zero value is honored, similar to NumPy.",
AttributeProto::INT,
static_cast<int64_t>(0))
.Input(0, "data", "An input tensor.", "T", OpSchema::Single, true, 1, OpSchema::Differentiable)
.Input(
1,
"shape",
"Specified shape for output.",
"tensor(int64)",
OpSchema::Single,
true,
1,
OpSchema::NonDifferentiable)
.Output(0, "reshaped", "Reshaped data.", "T", OpSchema::Single, true, 1, OpSchema::Differentiable)
.TypeConstraint(
"T",
OpSchema::all_tensor_types_with_bfloat(),
"Constrain input and output types to all tensor types.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
// Type inference
propagateElemTypeFromInputToOutput(ctx, 0, 0);
// Shape Inference if 2nd input data (the target shape) is available
// or the target shape is generated via partial data propagation
const TensorProto* targetShapeInitializer = ctx.getInputData(1);
const auto* shapeInput = ctx.getSymbolicInput(1);
// The targetShapeProto represents the specified shape for output.
TensorShapeProto targetShapeProto;
if (targetShapeInitializer) {
auto targetShape = ParseData<int64_t>(targetShapeInitializer);
for (auto val : targetShape) {
targetShapeProto.add_dim()->set_dim_value(val);
}
} else if (shapeInput) {
targetShapeProto.CopyFrom(*shapeInput);
} else {
return;
}
int allowzero = static_cast<int>(getAttribute(ctx, "allowzero", 0));
// Iterate through targetShape, adding dimensions in the outputShape
// TensorProto. If the targetShape dimension is -1, we do not set the
// dimension value in this iteration, but we record the Dimension. If
// targetShape dimension is 0, we attempt to propagate the dimension
// value/param. If the value cannot be inferred, we set the flag in
// the unresolveZeros vector. If targetShape dimension is positive, we
// set the dimension value in the outputShape. We track the product of
// the dimensions we are setting outputShape in the outputProduct
// variable. The outputProduct will potentially be used for inferring
// a dimension marked -1.
auto* outputShape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
TensorShapeProto::Dimension* negativeOneDim = nullptr;
const auto& dataInputTensorType = ctx.getInputType(0)->tensor_type();
std::vector<bool> unresolvedZeros(targetShapeProto.dim_size(), false);
int64_t outputProduct = 1;
bool outputProductValid = true;
for (int i = 0; i < static_cast<int>(targetShapeProto.dim_size()); ++i) {
// Add a new dimension to outputShape
auto* new_dim = outputShape->add_dim();
if (targetShapeProto.dim(i).has_dim_param()) {
// There is a tricky edge case here. It is possible that the value of
// symbolic dim can be -1 or 0 at runtime. In that case simply propgating this
// symbol can be erroneous. This should be a very rare scenario and in such a
// case an option is to turn off data propagation during shape inference.
new_dim->set_dim_param(targetShapeProto.dim(i).dim_param());
outputProductValid = false;
} else {
if (!targetShapeProto.dim(i).has_dim_value()) {
outputProductValid = false;
// treat this dim as unknown dim
continue;
}
const auto dim_value = targetShapeProto.dim(i).dim_value();
if (dim_value == -1) {
// Check if multiple -1's. If not, set negativeOneDim, marking
// this dimension to potentially be filled in later.
if (negativeOneDim) {
fail_shape_inference("Target shape may not have multiple -1 dimensions.");
}
negativeOneDim = new_dim;
} else if (dim_value == 0) {
// Check if data input has a shape and if the index i is within
// its bounds. If these conditions are satisfied, any dimension
// value/param should be propogated. If dimension value cannot be
// inferred, set the corresponding unresolvedZeros flag to true.
// If allowzero is set however, do not propagate values, since output
// dimension is explicitly zero.
if (allowzero == 0) {
unresolvedZeros[i] = true;
if (dataInputTensorType.has_shape()) {
if (i >= dataInputTensorType.shape().dim_size()) {
fail_shape_inference("Invalid position of 0.");
}
if (dataInputTensorType.shape().dim(i).has_dim_value()) {
const auto& input_dim_value = dataInputTensorType.shape().dim(i).dim_value();
new_dim->set_dim_value(input_dim_value);
outputProduct *= input_dim_value;
unresolvedZeros[i] = false;
} else if (dataInputTensorType.shape().dim(i).has_dim_param()) {
new_dim->set_dim_param(dataInputTensorType.shape().dim(i).dim_param());
}
}
} else {
new_dim->set_dim_value(dim_value);
outputProduct *= dim_value;
}
} else if (dim_value > 0) {
// Set the dimension value to dim_value
new_dim->set_dim_value(dim_value);
outputProduct *= dim_value;
} else {
// Check if value is less than -1; fail if so
fail_shape_inference("Invalid dimension value: ", dim_value);
}
}
}
// If negativeOneDim has been set, we attempt to infer its value. This
// can be done if all dimension values for the data input tensor shape
// are known other than the ones corresponding to unresolvedZeros
// flags.
if (negativeOneDim && outputProductValid) {
// First, attempt to compute product of data input shape dimensions
// that are not marked by unresolvedZeros. If not possible, set the
// inputProductValid flag to false.
if (!outputProduct) {
fail_shape_inference("Invalid Target shape product of 0. Product cannot be 0 in combination with -1");
}
int64_t inputProduct = 1;
bool inputProductValid = true;
if (!dataInputTensorType.has_shape()) {
inputProductValid = false;
} else {
for (int i = 0; i < dataInputTensorType.shape().dim_size(); ++i) {
if (dataInputTensorType.shape().dim(i).has_dim_value()) {
inputProduct *= dataInputTensorType.shape().dim(i).dim_value();
} else if (i >= static_cast<int>(unresolvedZeros.size()) || !unresolvedZeros[i]) {
inputProductValid = false;
break;
}
}
}
if (inputProductValid) {
if (inputProduct % outputProduct != 0) {
fail_shape_inference("Dimension could not be inferred: incompatible shapes");
}
negativeOneDim->set_dim_value(inputProduct / outputProduct);
}
}
}));
static const char* Shape_ver15_doc = R"DOC(
Takes a tensor as input and outputs an 1D int64 tensor containing the shape of the input tensor.
Optional attributes start and end can be used to compute a slice of the input tensor's shape.
If start axis is omitted, the slice starts from axis 0.
The end axis, if specified, is exclusive (and the returned value will not include the size of that axis).
If the end axis is omitted, the axes upto the last one will be included.
Negative axes indicate counting back from the last axis.
Note that axes will be clipped to the range [0, r-1], where r is the
rank of the input tensor if they are out-of-range (after adding r in the case of
negative axis). Thus, specifying any end value > r is equivalent to specifying an end
value of r, and specifying any start value < -r is equivalent to specifying a start
value of 0.
For example:
Input tensor with shape: [2, 3, 4]
No attributes specified.
Output: [2, 3, 4]
Input tensor with shape: [2, 3, 4]
start: -1
Output: [4]
Input tensor with shape: [2, 3, 4]
end: -1
Output: [2, 3]
Input tensor with shape: [2, 3, 4]
start: 1
end: 2
Output: [3]
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Shape,
15,
OpSchema()
.SetDoc(Shape_ver15_doc)
.Input(0, "data", "An input tensor.", "T", OpSchema::Single, true, 1, OpSchema::NonDifferentiable)
.Output(0, "shape", "Shape of the input tensor", "T1", OpSchema::Single, true, 1, OpSchema::NonDifferentiable)
.Attr(
"start",
"(Optional) Starting axis for slicing the shape. Default value is 0."
"Negative value means counting dimensions from the back.",
AttributeProto::INT,
static_cast<int64_t>(0))
.Attr(
"end",
"(Optional) Ending axis for slicing the shape. "
"Negative value means counting dimensions from the back. "
"If omitted, sizes of all axes upto (including) the last one will be included.",
AttributeProto::INT,
OPTIONAL_VALUE)
.TypeConstraint("T", OpSchema::all_tensor_types_with_bfloat(), "Input tensor can be of arbitrary type.")
.TypeConstraint("T1", {"tensor(int64)"}, "Constrain output to int64 tensor.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
ctx.getOutputType(0)->mutable_tensor_type()->set_elem_type(TensorProto::INT64);
auto* output_shape = ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
auto* output_length = output_shape->add_dim();
if (!hasNInputShapes(ctx, 1)) {
return;
}
int64_t rank = static_cast<int64_t>(ctx.getInputType(0)->tensor_type().shape().dim_size());
int64_t start = getAttribute(ctx, "start", 0);
if (start < 0)
start += rank;
start = (start < 0) ? 0 : (start > rank) ? rank : start;
int64_t end = getAttribute(ctx, "end", rank);
if (end < 0)
end += rank;
end = (end < 0) ? 0 : (end > rank) ? rank : end;
output_length->set_dim_value((end - start) < 0 ? 0 : (end - start));
})
.PartialDataPropagationFunction([](DataPropagationContext& ctx) {
if (ctx.getInputType(0)->tensor_type().has_shape()) {
auto& input_shape = ctx.getInputType(0)->tensor_type().shape();
int64_t rank = static_cast<int64_t>(input_shape.dim_size());
int64_t start = getAttribute(ctx, "start", 0);
if (start < 0)
start += rank;
start = (start < 0) ? 0 : (start > rank) ? rank : start;
int64_t end = getAttribute(ctx, "end", rank);
if (end < 0)
end += rank;
end = (end < 0) ? 0 : (end > rank) ? rank : end;
TensorShapeProto output_shape;
for (int64_t d = start; d < end; ++d) {
*output_shape.add_dim() = input_shape.dim(static_cast<int>(d));
}
ctx.addOutputData(0, std::move(output_shape));
}
}));
static const char* Size_ver13_doc = R"DOC(
Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Size,
13,
OpSchema()
.SetDoc(Size_ver13_doc)
.Input(0,
"data",
"An input tensor.",
"T",
OpSchema::Single,
true,
1,
OpSchema::NonDifferentiable)
.Output(0,
"size",
"Total number of elements of the input tensor",
"T1",
OpSchema::Single,
true,
1,
OpSchema::NonDifferentiable)
.TypeConstraint(
"T",
OpSchema::all_tensor_types_with_bfloat(),
"Input tensor can be of arbitrary type.")
.TypeConstraint(
"T1",
{"tensor(int64)"},
"Constrain output to int64 tensor, which should be a scalar though.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
ctx.getOutputType(0)->mutable_tensor_type()->set_elem_type(
TensorProto::INT64);
ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
})
.PartialDataPropagationFunction([](DataPropagationContext& ctx) {
const auto input_data = ctx.getInputData(0);
if (input_data != nullptr) {
TensorShapeProto tsp;
tsp.mutable_dim()->Add()->set_dim_value(input_data->dim_size());
ctx.addOutputData(0, std::move(tsp));
}
}));
ONNX_OPERATOR_SET_SCHEMA(
Concat,
13,
OpSchema()
.Attr(
"axis",
"Which axis to concat on. A negative value means counting dimensions from the back. "
"Accepted range is [-r, r-1] where r = rank(inputs)..",
AttributeProto::INT)
.SetDoc(
"Concatenate a list of tensors into a single tensor. "
"All input tensors must have the same shape, except for the dimension size of the axis to concatenate on.")
.Input(
0,
"inputs",
"List of tensors for concatenation",
"T",
OpSchema::Variadic,
true,
1,
OpSchema::Differentiable)
.Output(
0,
"concat_result",
"Concatenated tensor",
"T",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.TypeConstraint(
"T",
OpSchema::all_tensor_types_with_bfloat(),
"Constrain output types to any tensor type.")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
propagateElemTypeFromInputToOutput(ctx, 0, 0);
auto numInputs = ctx.getNumInputs();
if (numInputs < 1 ||
!hasNInputShapes(ctx, static_cast<int>(numInputs))) {
return;
}
auto rank = ctx.getInputType(0)->tensor_type().shape().dim_size();
auto axisAttr = ctx.getAttribute("axis");
if (!axisAttr) {
fail_shape_inference("Required attribute axis is missing");
}
int axis = static_cast<int>(axisAttr->i());
if (axis < -rank || axis >= rank) {
fail_shape_inference("axis must be in [-rank, rank-1].");
}
if (axis < 0) {
axis += rank;
}
if (numInputs == 1) {
propagateShapeFromInputToOutput(ctx, 0, 0);
return;
}
bool all_lengths_known = true;
int total_length = 0;
auto* output_shape =
ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
for (int64_t i = 0; i < rank; ++i) {
output_shape->add_dim();
}
for (size_t i = 0; i < numInputs; i++) {
const auto& shape = ctx.getInputType(i)->tensor_type().shape();
if (shape.dim_size() != rank) {
fail_shape_inference("All inputs to Concat must have same rank");
}
for (int j = 0; j < rank; j++) {
if (j == axis) {
if (shape.dim(j).has_dim_value()) {
total_length += static_cast<int>(shape.dim(j).dim_value());
} else {
all_lengths_known = false;
}
} else {
auto& output_dim = *output_shape->mutable_dim(j);
const auto& input_dim = shape.dim(j);
mergeInDimensionInfo(input_dim, output_dim, j);
}
}
}
if (all_lengths_known) {
output_shape->mutable_dim(axis)->set_dim_value(total_length);
}
})
.PartialDataPropagationFunction([](DataPropagationContext& ctx) {
if (!axisIsZero(ctx)) {
return;
}
TensorShapeProto tsp;
for (size_t i = 0; i < ctx.getNumInputs(); ++i) {
const auto input_data = ctx.getInputData(i);
if (input_data == nullptr) {
return;
}
for (int j = 0; j < input_data->dim_size(); ++j) {
appendDimToTensorShapeProto(tsp, input_data->dim(j));
}
}
if (tsp.dim_size() > 0) {
ctx.addOutputData(0, std::move(tsp));
}
}));
static const char* Split_ver13_doc =
R"DOC(Split a tensor into a list of tensors, along the specified
'axis'. Lengths of the parts can be specified using input 'split'.
Otherwise, the tensor is split to equal sized parts.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Split,
13,
OpSchema()
.Input(
0,
"input",
"The tensor to split",
"T",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.Input(
1,
"split",
"Optional length of each output. Values should be >= 0."
"Sum of the values must be equal to the dim value at 'axis' specified.",
"tensor(int64)",
OpSchema::Optional,
true,
1,
OpSchema::NonDifferentiable)
.Output(
0,
"outputs",
"One or more outputs forming list of tensors after splitting",
"T",
OpSchema::Variadic,
true,
1,
OpSchema::Differentiable)
.TypeConstraint(
"T",
OpSchema::all_tensor_types_with_bfloat(),
"Constrain input and output types to all tensor types.")
.Attr(
"axis",
"Which axis to split on. "
"A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1] "
"where r = rank(input).",
AttributeProto::INT,
static_cast<int64_t>(0))
.SetDoc(Split_ver13_doc)
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
for (int i = 0; i < static_cast<int>(ctx.getNumOutputs()); ++i) {
propagateElemTypeFromInputToOutput(ctx, 0, i);
}
if (!hasNInputShapes(ctx, 1)) {
return;
}
const auto& shape = ctx.getInputType(0)->tensor_type().shape();
int rank = shape.dim_size();
int axis = static_cast<int>(getAttribute(ctx, "axis", 0));
if (axis < -rank || axis >= rank) {
fail_type_inference(
"Invalid value of attribute 'axis'. Rank=",
rank,
" Value=",
axis);
}
if (axis < 0) {
axis += rank;
}
const auto& split_dim = shape.dim(axis);
if (!split_dim.has_dim_value()) {
for (size_t i = 0; i < ctx.getNumOutputs(); i++) {
*ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() =
shape;
ctx.getOutputType(i)
->mutable_tensor_type()
->mutable_shape()
->mutable_dim(axis)
->Clear();
}
return;
}
int split_dim_value = static_cast<int>(split_dim.dim_value());
std::vector<int64_t> split;
size_t num_inputs = ctx.getNumInputs();
if ((num_inputs == 2) && ctx.getInputType(1)) { //'split' is input
auto split_proto = ctx.getInputData(1);
if (split_proto == nullptr) {
// skip if split is not an initializer
return;
}
split = ParseData<int64_t>(split_proto);
if (split.size() != ctx.getNumOutputs()) {
fail_shape_inference(
"Mismatch between number of splits (",
split.size(),
") and outputs (",
ctx.getNumOutputs(),
")");
}
int64_t total_dim = 0;
for (int64_t d : split) {
total_dim += d;
}
if (total_dim != split_dim_value) {
fail_shape_inference(
"Mismatch between the sum of 'split' (",
total_dim,
") and the split dimension of the input (",
split_dim_value,
")");
}
} else { // no value available for 'split'
int num_outputs = static_cast<int>(ctx.getNumOutputs());
if (split_dim_value % num_outputs != 0) {
fail_shape_inference("The input is not evenly splittable");
}
int chunk_size = split_dim_value / num_outputs;
split.reserve(ctx.getNumOutputs());
for (int i = 0; i < static_cast<int>(ctx.getNumOutputs()); i++) {
split.push_back(chunk_size);
}
}
for (size_t i = 0; i < ctx.getNumOutputs(); i++) {
*ctx.getOutputType(i)->mutable_tensor_type()->mutable_shape() =
shape;
ctx.getOutputType(i)
->mutable_tensor_type()
->mutable_shape()
->mutable_dim(axis)
->set_dim_value(split[i]);
}
}));
static const char* Slice_ver13_doc = R"DOC(
Produces a slice of the input tensor along multiple axes. Similar to numpy:
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
Slices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end
dimension and step for each axis in the list of axes, it uses this information to
slice the input `data` tensor. If a negative value is passed for any of the
start or end indices, it represents number of elements before the end of that
dimension. If the value passed to start or end is larger than the `n` (the
number of elements in this dimension), it represents `n`. For slicing to the
end of a dimension with unknown size, it is recommended to pass in `INT_MAX`
when sclicing forward and 'INT_MIN' when slicing backward.
If a negative value is passed for step, it represents slicing backward.
However step value cannot be 0.
If `axes` are omitted, they are set to `[0, ..., ndim-1]`.
If `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)`
Example 1:
data = [
[1, 2, 3, 4],
[5, 6, 7, 8],
]
axes = [0, 1]
starts = [1, 0]
ends = [2, 3]
steps = [1, 2]
result = [
[5, 7],
]
Example 2:
data = [
[1, 2, 3, 4],
[5, 6, 7, 8],
]
starts = [0, 1]
ends = [-1, 1000]
result = [
[2, 3, 4],
]
)DOC";
inline void processSliceInputs(const int64_t input_rank,
int64_t& start, int64_t& end, int64_t& step) {
auto clamp = [](int64_t val, int64_t min, int64_t max) -> int64_t {
return (val < min) ? min : (val > max) ? max : val;
};
// process step
if (step == 0) {
fail_shape_inference("'step' cannot be 0 for Slice");
}
// process start
if (start < 0)
start += input_rank;
if (step < 0)
start = clamp(start, 0, input_rank - 1);
else
start = clamp(start, 0, input_rank);
// process end
if (end < 0)
end += input_rank;
if (step < 0)
end = clamp(end, -1, input_rank);
else
end = clamp(end, 0, input_rank);
}
ONNX_OPERATOR_SET_SCHEMA(
Slice,
13,
OpSchema()
.SetDoc(Slice_ver13_doc)
.Input(
0,
"data",
"Tensor of data to extract slices from.",
"T",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.Input(
1,
"starts",
"1-D tensor of starting indices of corresponding axis in `axes`",
"Tind",
OpSchema::Single,
true,
1,
OpSchema::NonDifferentiable)
.Input(
2,
"ends",
"1-D tensor of ending indices (exclusive) of corresponding axis in `axes`",
"Tind",
OpSchema::Single,
true,
1,
OpSchema::NonDifferentiable)
.Input(
3,
"axes",
"1-D tensor of axes that `starts` and `ends` apply to. Negative value means counting dimensions "
"from the back. Accepted range is [-r, r-1] where r = rank(data).",
"Tind",
OpSchema::Optional,
true,
1,
OpSchema::NonDifferentiable)
.Input(
4,
"steps",
"1-D tensor of slice step of corresponding axis in `axes`. "
"Negative value means slicing backward. 'steps' cannot be 0. "
"Defaults to 1.",
"Tind",
OpSchema::Optional,
true,
1,
OpSchema::NonDifferentiable)
.Output(
0,
"output",
"Sliced data tensor.",
"T",
OpSchema::Single,
true,
1,
OpSchema::Differentiable)
.TypeConstraint(
"T",
OpSchema::all_tensor_types_with_bfloat(),
"Constrain input and output types to all tensor types.")
.TypeConstraint(
"Tind",
{"tensor(int32)", "tensor(int64)"},
"Constrain indices to integer types")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
size_t num_inputs = ctx.getNumInputs();
if (num_inputs != 3 && num_inputs != 4 && num_inputs != 5) {
fail_type_inference(
"Slice op must have either three, four or five inputs.");
}
propagateElemTypeFromInputToOutput(ctx, 0, 0);
if (!hasNInputShapes(ctx, 1)) {
return;
}
// Shape Inference if
// 1. 2nd and 3rd input data (starts, ends) are available.
// and 2. 4th and 5th optional input (axes, steps) are either not set,
// or set and is initializer.
const TensorProto* startsInitializer = ctx.getInputData(1);
const TensorProto* endsInitializer = ctx.getInputData(2);
const TensorProto* axesInitializer =
hasInputShape(ctx, 3) ? ctx.getInputData(3) : nullptr;
const TensorProto* stepsInitializer =
hasInputShape(ctx, 4) ? ctx.getInputData(4) : nullptr;
if (!startsInitializer || !endsInitializer ||
(hasInputShape(ctx, 3) && !ctx.getInputData(3)) ||
(hasInputShape(ctx, 4) && !ctx.getInputData(4))) {
return;
}
// don't know data_type- can't proceed
if (!startsInitializer->has_data_type())
return;
auto get_initializer_data =
[](const TensorProto* initializer) -> std::vector<int64_t> {
std::vector<int64_t> vec;
if (initializer->data_type() == TensorProto::INT64) {
const auto& data = ParseData<int64_t>(initializer);
vec.insert(vec.end(), data.begin(), data.end());
} else if (initializer->data_type() == TensorProto::INT32) {
const auto& data = ParseData<int32_t>(initializer);
vec.insert(vec.end(), data.begin(), data.end());
} else {
// unaccepted data type
fail_shape_inference(
"Only supports `int32_t` or `int64_t` inputs for starts/ends/axes/steps");
}
return vec;
};
std::vector<int64_t> starts = get_initializer_data(startsInitializer);
std::vector<int64_t> ends = get_initializer_data(endsInitializer);
if (starts.size() != ends.size()) {
fail_shape_inference(
"Incorrect or missing input value for starts and ends");
}
const auto& input_shape = ctx.getInputType(0)->tensor_type().shape();
const auto input_rank = input_shape.dim_size();
std::vector<int64_t> axes(starts.size());
if (!axesInitializer) {
std::iota(axes.begin(), axes.end(), 0);
} else {
axes = get_initializer_data(axesInitializer);
if (axes.size() != starts.size()) {
fail_shape_inference("Input axes has incorrect length");
}
}
std::vector<int64_t> steps;
if (!stepsInitializer) {
steps = std::vector<int64_t>(starts.size(), 1);
} else {
steps = get_initializer_data(stepsInitializer);
if (steps.size() != axes.size()) {
fail_shape_inference("Input steps has incorrect length");
}
}
for (size_t i = 0; (int64_t)i < input_rank; ++i) {
// first update rank of output dim
auto* output_dim = ctx.getOutputType(0)
->mutable_tensor_type()
->mutable_shape()
->add_dim();
const auto& input_dim = input_shape.dim((int)i);
if (input_dim.has_dim_value()) {
output_dim->set_dim_value(input_dim.dim_value());
} else if (input_dim.has_dim_param()) {
output_dim->set_dim_param(input_dim.dim_param());
}
}
std::unordered_set<int64_t> unique_axes;
size_t axes_size = axes.size();
for (size_t axis_index = 0; axis_index < axes_size; ++axis_index) {
auto axis = axes[axis_index] < 0
? axes[axis_index] + static_cast<int64_t>(input_rank)
: axes[axis_index];