Repository navigation
Expand file tree
/
Copy pathdefs.cc
More file actions
1820 lines (1687 loc) · 70.6 KB
/
Copy pathdefs.cc
File metadata and controls
1820 lines (1687 loc) · 70.6 KB
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) ONNX Project Contributors.
// Licensed under the MIT license.
#include <algorithm>
#include <cmath>
#include "onnx/defs/function.h"
#include "onnx/defs/schema.h"
using namespace ONNX_NAMESPACE;
namespace ONNX_NAMESPACE {
const char* pads_doc =
"Padding for the beginning and ending along each axis, it can take any value greater "
"than or equal to 0. The value represent the number of pixels added to the beginning "
"and end part of the corresponding axis. `pads` format should be as follow "
"[x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels "
"added at the beginning of axis `i` and xi_end, the number of pixels added at "
"the end of axis `i`. This attribute cannot be used simultaneously with "
"auto_pad attribute. If not present, the padding defaults to 0 along start and end of each axis.";
const char* auto_pad_doc =
"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where "
"default value is NOTSET, which means explicit padding is used. "
"SAME_UPPER or SAME_LOWER mean pad the input so that the output size match the input."
"In case of odd number add the extra padding at the end for SAME_UPPER and at the "
"beginning for SAME_LOWER. VALID mean no padding. DEPRECATION NOTE: auto_pad is "
"only intended to support legacy uses, and for framework authors, one is explicitly "
"encouraged to use explicit padding specified in the pads attribute.";
} // namespace ONNX_NAMESPACE
namespace ONNX_NAMESPACE {
void convPoolTypeAndShapeInference(
InferenceContext& ctx,
bool use_dilation,
bool require_kernel_shape) {
propagateElemTypeFromInputToOutput(ctx, 0, 0);
if (ctx.getNumOutputs() > 1) {
// MaxPool with two outputs case.
auto output_type = ctx.getOutputType(1);
if (output_type->value_case() == TypeProto::kTensorType ||
output_type->value_case() == TypeProto::VALUE_NOT_SET) {
output_type->mutable_tensor_type()->set_elem_type(TensorProto::INT64);
}
}
// we need the first input shape for this inference.
if (!hasNInputShapes(ctx, 1)) {
return;
}
// if kernel shape is an input (and not attribute)
// we need the shape of the second input.
if (!require_kernel_shape && !hasNInputShapes(ctx, 2)) {
return;
}
// don't bother with legacy auto_pad for now
const auto* auto_pad_attr = ctx.getAttribute("auto_pad");
if ((nullptr != auto_pad_attr) && (auto_pad_attr->s() != "NOTSET")) {
return;
}
auto input_shape = ctx.getInputType(0)->tensor_type().shape();
if (input_shape.dim_size() < 2) {
fail_shape_inference("Input tensor must have atleast 2 dimensions");
}
// first dim is the batch axis and the next is the number of channels.
size_t n_input_dims = static_cast<size_t>(input_shape.dim_size() - 2);
// Pooling operations don't support dilation, only Conv. For
// simplicity of the code, we just treat them as having all-1s
// dilation.
std::vector<int64_t> dilations;
if (use_dilation && getRepeatedAttribute(ctx, "dilations", dilations)) {
if (dilations.size() != n_input_dims) {
fail_shape_inference("Attribute dilations has incorrect size");
}
} else {
dilations.assign(n_input_dims, 1);
}
std::vector<int64_t> pads;
if (getRepeatedAttribute(ctx, "pads", pads)) {
if (pads.size() != n_input_dims * 2) {
fail_shape_inference("Attribute pads has incorrect size");
}
} else {
pads.assign(n_input_dims * 2, 0);
}
std::vector<int64_t> strides;
if (getRepeatedAttribute(ctx, "strides", strides)) {
if (strides.size() != n_input_dims) {
fail_shape_inference("Attribute strides has incorrect size");
}
} else {
strides.assign(n_input_dims, 1);
}
std::vector<int64_t> kernel_shape;
if (getRepeatedAttribute(ctx, "kernel_shape", kernel_shape)) {
if (kernel_shape.size() != n_input_dims) {
fail_shape_inference("Attribute kernel_shape has incorrect size");
}
} else if (require_kernel_shape) {
fail_shape_inference("Attribute kernel_shape must be specified");
} else {
auto second_input_shape = ctx.getInputType(1)->tensor_type().shape();
for (int i = 2; i < second_input_shape.dim_size(); ++i) {
if (!second_input_shape.dim(i).has_dim_value()) {
return;
}
kernel_shape.push_back(second_input_shape.dim(i).dim_value());
}
}
auto output_shape =
ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
if (require_kernel_shape) {
// add the first two dimensions from the input.
*output_shape->add_dim() = input_shape.dim(0);
*output_shape->add_dim() = input_shape.dim(1);
} else {
*output_shape->add_dim() = input_shape.dim(0);
auto& second_input_shape = getInputShape(ctx, 1);
if (second_input_shape.dim_size() < 1) {
fail_shape_inference("Second input tensor has wrong dimension");
}
*output_shape->add_dim() = second_input_shape.dim(0);
}
int kernel_shape_size = static_cast<int>(kernel_shape.size());
for (int i = 0; i < kernel_shape_size; ++i) {
auto newdim = output_shape->add_dim();
if (!input_shape.dim(2 + i).has_dim_value()) {
continue;
}
// how big is the input, including padding
int64_t effective_input_size = input_shape.dim(2 + i).dim_value();
effective_input_size += pads[i];
effective_input_size += pads[i + kernel_shape_size];
int64_t effective_kernel_size = kernel_shape[i];
// accounting for dilation, how big is the kernel in this dimension
effective_kernel_size = (effective_kernel_size - 1) * dilations[i] + 1;
bool ceil_mode = ctx.getAttribute("ceil_mode");
// how many times we can move the kernel from it's initial position, based
// on the stride
int64_t strided_kernel_positions;
if (ceil_mode)
strided_kernel_positions = (int64_t)(std::ceil(
(effective_input_size - effective_kernel_size) / float(strides[i])));
else
strided_kernel_positions =
(effective_input_size - effective_kernel_size) / strides[i];
// add in the initial position
newdim->set_dim_value(1 + strided_kernel_positions);
}
if (ctx.getNumOutputs() > 1) {
// MaxPool with two outputs case.
auto second_output_shape =
ctx.getOutputType(1)->mutable_tensor_type()->mutable_shape();
second_output_shape->CopyFrom(*output_shape);
}
}
std::function<void(OpSchema&)> PoolOpSchemaGenerator_9(
const char* name,
const char* opName,
const char* additionalDescription) {
return [=](OpSchema& schema) {
std::string doc = R"DOC(
{name} consumes an input tensor X and applies {opName} pooling across
the tensor according to kernel sizes, stride sizes, and pad lengths.
{opName} pooling consisting of computing the {opName} on all values of a
subset of the input tensor according to the kernel size and downsampling the
data into the output tensor Y for further processing. The output spatial shape will be following:
```
output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)
* pad_shape[i] is sum of pads along axis i
```
`auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:
```
VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])
SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])
```
And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:
```
pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]
```
{additionalDescription}
)DOC";
ReplaceAll(doc, "{name}", name);
ReplaceAll(doc, "{opName}", opName);
ReplaceAll(doc, "{additionalDescription}", additionalDescription);
schema.SetDoc(doc);
schema.Attr(
"kernel_shape",
"The size of the kernel along each axis.",
AttributeProto::INTS);
schema.Attr(
"strides", "Stride along each axis.", AttributeProto::INTS, OPTIONAL);
schema.Attr(
"auto_pad",
auto_pad_doc,
AttributeProto::STRING,
std::string("NOTSET"));
schema.Attr("pads", pads_doc, AttributeProto::INTS, OPTIONAL);
schema.Input(
0,
"X",
"Input data tensor from the previous operator; "
"dimensions for image case are (N x C x H x W), "
"where N is the batch size, C is the number of "
"channels, and H and W are the height and the "
"width of the data. For non image case, the "
"dimensions are in the form of "
"(N x C x D1 x D2 ... Dn), where N is the batch "
"size. Optionally, if dimension denotation is "
"in effect, the operation expects the input "
"data tensor to arrive with the dimension denotation "
"of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].",
"T");
schema.Output(
0,
"Y",
"Output data tensor from average or max pooling across "
"the input tensor. Dimensions will vary based "
"on various kernel, stride, and pad sizes. Floor value of "
"the dimension is used",
"T");
schema.TypeConstraint(
"T",
{"tensor(float16)", "tensor(float)", "tensor(double)"},
"Constrain input and output types to float tensors.");
schema.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
convPoolTypeAndShapeInference(ctx, false, true);
});
};
} // namespace ONNX_NAMESPACE
std::function<void(OpSchema&)> PoolOpSchemaGenerator(
const char* name,
const char* opName,
const char* additionalDescription,
bool use_dilation) {
return [=](OpSchema& schema) {
std::string doc = R"DOC(
{name} consumes an input tensor X and applies {opName} pooling across
the tensor according to kernel sizes, stride sizes, and pad lengths.
{opName} pooling consisting of computing the {opName} on all values of a
subset of the input tensor according to the kernel size and downsampling the
data into the output tensor Y for further processing. The output spatial shape will be following:
```
output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)
```
or
```
output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)
```
if ceil_mode is enabled
```
* pad_shape[i] is sum of pads along axis i
```
`auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:
```
VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])
SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])
```
And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:
```
pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]
```
{additionalDescription}
)DOC";
ReplaceAll(doc, "{name}", name);
ReplaceAll(doc, "{opName}", opName);
ReplaceAll(doc, "{additionalDescription}", additionalDescription);
schema.SetDoc(doc);
schema.Attr(
"kernel_shape",
"The size of the kernel along each axis.",
AttributeProto::INTS);
schema.Attr(
"strides", "Stride along each axis.", AttributeProto::INTS, OPTIONAL);
schema.Attr(
"auto_pad",
auto_pad_doc,
AttributeProto::STRING,
std::string("NOTSET"));
schema.Attr("pads", pads_doc, AttributeProto::INTS, OPTIONAL);
schema.Attr(
"ceil_mode",
"Wether to use ceil or floor (default) to compute the output shape.",
AttributeProto::INT,
static_cast<int64_t>(0));
schema.Input(
0,
"X",
"Input data tensor from the previous operator; "
"dimensions for image case are (N x C x H x W), "
"where N is the batch size, C is the number of "
"channels, and H and W are the height and the "
"width of the data. For non image case, the "
"dimensions are in the form of "
"(N x C x D1 x D2 ... Dn), where N is the batch "
"size. Optionally, if dimension denotation is "
"in effect, the operation expects the input "
"data tensor to arrive with the dimension denotation "
"of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].",
"T");
schema.Output(
0,
"Y",
"Output data tensor from average or max pooling across "
"the input tensor. Dimensions will vary based "
"on various kernel, stride, and pad sizes. Floor value of "
"the dimension is used",
"T");
schema.TypeConstraint(
"T",
{"tensor(float16)", "tensor(float)", "tensor(double)"},
"Constrain input and output types to float tensors.");
schema.TypeAndShapeInferenceFunction([use_dilation](InferenceContext& ctx) {
convPoolTypeAndShapeInference(ctx, use_dilation, true);
});
};
} // namespace ONNX_NAMESPACE
ONNX_OPERATOR_SET_SCHEMA(
AveragePool,
1,
OpSchema().FillUsing(PoolOpSchemaGenerator_9(
"AveragePool",
"average",
"The output of each pooling window is divided by the number of elements exclude pad.")));
ONNX_OPERATOR_SET_SCHEMA(
AveragePool,
7,
OpSchema()
.FillUsing(PoolOpSchemaGenerator_9(
"AveragePool",
"average",
"The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero)."))
.Attr(
"count_include_pad",
"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.",
AttributeProto::INT,
static_cast<int64_t>(0)));
ONNX_OPERATOR_SET_SCHEMA(
AveragePool,
10,
OpSchema()
.FillUsing(PoolOpSchemaGenerator(
"AveragePool",
"average",
"The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).",
false))
.Attr(
"count_include_pad",
"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.",
AttributeProto::INT,
static_cast<int64_t>(0)));
ONNX_OPERATOR_SET_SCHEMA(
MaxPool,
1,
OpSchema().FillUsing(PoolOpSchemaGenerator_9(
"MaxPool",
"max",
"The output of each pooling window is maximum number of elements exclude pad.")));
ONNX_OPERATOR_SET_SCHEMA(
MaxPool,
8,
OpSchema()
.FillUsing(PoolOpSchemaGenerator_9(
"MaxPool",
"max",
"The output of each pooling window is maximum number of elements exclude pad."))
.Attr(
"storage_order",
"The storage order of the tensor. 0 is row major, and 1 is column major.",
AttributeProto::INT,
static_cast<int64_t>(0))
.Output(
1,
"Indices",
"Indices tensor from max pooling across the input tensor. "
"The dimensions of indices are the same as output tensor. "
"The values in indices of are the indices of the selected values during pooling. "
"The indices are computed as flatten 1-D tensor, "
"and the indices do not consider padding. "
"So the values in indices are in [0, N x C x D1 x ... x Dn).",
"I",
OpSchema::Optional)
.TypeConstraint(
"I",
{"tensor(int64)"},
"Constrain index tensor to int64"));
ONNX_OPERATOR_SET_SCHEMA(
MaxPool,
10,
OpSchema()
.FillUsing(PoolOpSchemaGenerator(
"MaxPool",
"max",
"The output of each pooling window is maximum number of elements exclude pad.",
true))
.Attr(
"storage_order",
"The storage order of the tensor. 0 is row major, and 1 is column major.",
AttributeProto::INT,
static_cast<int64_t>(0))
.Attr(
"dilations",
"Dilation value along each axis of filter.",
AttributeProto::INTS,
OPTIONAL)
.Output(
1,
"Indices",
"Indices tensor from max pooling across the input tensor. "
"The dimensions of indices are the same as output tensor. "
"The values in indices of are the indices of the selected values during pooling. "
"The indices are computed as flatten 1-D tensor, "
"and the indices do not consider padding. "
"So the values in indices are in [0, N x C x D1 x ... x Dn).",
"I",
OpSchema::Optional)
.TypeConstraint(
"I",
{"tensor(int64)"},
"Constrain index tensor to int64"));
void maxUnpoolShapeInference(InferenceContext& ctx) {
// we need at least two inputs to have a shape for this inference.
if (ctx.getNumInputs() != 2 && ctx.getNumInputs() != 3) {
fail_type_inference("MaxUnpool op must have either two or three inputs.");
}
propagateElemTypeFromInputToOutput(ctx, 0, 0);
if (!hasInputShape(ctx, 0)) {
return; // If first input does not have shape, we cannot infer much.
}
auto input_shape = ctx.getInputType(0)->tensor_type().shape();
if (input_shape.dim_size() < 2) {
fail_shape_inference("Input tensor X must have atleast 2 dimensions.");
}
// first dim is the batch axis and the next is the number of channels.
size_t n_input_dims = static_cast<size_t>(input_shape.dim_size() - 2);
std::vector<int64_t> pads;
if (getRepeatedAttribute(ctx, "pads", pads)) {
if (pads.size() != n_input_dims * 2) {
fail_shape_inference("Attribute pads has incorrect size.");
}
} else {
pads.assign(n_input_dims * 2, 0);
}
std::vector<int64_t> strides;
if (getRepeatedAttribute(ctx, "strides", strides)) {
if (strides.size() != n_input_dims) {
fail_shape_inference("Attribute strides has incorrect size.");
}
} else {
strides.assign(n_input_dims, 1);
}
std::vector<int64_t> kernel_shape;
if (getRepeatedAttribute(ctx, "kernel_shape", kernel_shape)) {
if (kernel_shape.size() != n_input_dims) {
fail_shape_inference("Attribute kernel_shape has incorrect size.");
}
} else {
fail_shape_inference("Attribute kernel_shape must be specified.");
}
if (ctx.getNumInputs() == 3) {
// If the third input, output_size, is specified, then use that instead
// of inferring shape from inputs.
if (hasInputShape(ctx, 2)) {
auto& output_shape = getInputShape(ctx, 2);
if (output_shape.dim_size() != 1) {
fail_type_inference("'output_shape' must be rank 1 tensor.");
}
if (output_shape.dim((int)0).has_dim_value() &&
static_cast<int>(output_shape.dim((int)0).dim_value()) !=
input_shape.dim_size()) {
fail_shape_inference(
"'output_shape' must have same number of elements as the shape of input tensor X.");
}
}
return; // 'output_shape' is specified as input. Actual shape will be
// determined at runtime.
}
auto final_output_shape =
ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
*final_output_shape->add_dim() = input_shape.dim(0);
*final_output_shape->add_dim() =
ctx.getInputType(1)->tensor_type().shape().dim(
1); // channels should be the second dim of second input.
int kernel_shape_size = static_cast<int>(kernel_shape.size());
for (int i = 0; i < kernel_shape_size; ++i) {
auto newdim = final_output_shape->add_dim();
if (!input_shape.dim(2 + i).has_dim_value()) {
continue;
}
int64_t newdim_value =
strides[i] * (input_shape.dim(2 + i).dim_value() - 1);
newdim_value += kernel_shape[i];
newdim_value -= pads[i];
newdim_value -= pads[i + kernel_shape_size];
// add in the initial position
newdim->set_dim_value(newdim_value);
}
}
static const char* MaxUnpool_ver9_doc = R"DOC(
MaxUnpool essentially computes the partial inverse of the MaxPool op.
The input information to this op is typically the the output information from a MaxPool op. The first
input tensor X is the tensor that needs to be unpooled, which is typically the pooled tensor (first output)
from MaxPool. The second input tensor, I, contains the indices to the (locally maximal) elements corrsponding
to the elements in the first input tensor X. Input tensor I is typically the second output of the MaxPool op.
The third (optional) input is a tensor that specifies the output size of the unpooling operation.
MaxUnpool is intended to do 'partial' inverse of the MaxPool op. 'Partial' because all the non-maximal
values from the original input to MaxPool are set to zero in the output of the MaxUnpool op. Pooling
the result of an unpooling operation should give back the original input to the unpooling op.
MaxUnpool can produce the same output size for several input sizes, which makes unpooling op ambiguous.
The third input argument, output_size, is meant to disambiguate the op and produce output tensor of
known/predictable size.
In addition to the inputs, MaxUnpool takes three attributes, namely kernel_shape, strides, and pads,
which define the exact unpooling op. The attributes typically have the same values as the corrsponding
pooling op that the unpooling op is trying to invert.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
MaxUnpool,
9,
OpSchema()
.SetDoc(MaxUnpool_ver9_doc)
10BC8
div>
.Attr(
"kernel_shape",
"The size of the kernel along each axis.",
AttributeProto::INTS)
.Attr(
"strides",
"Stride along each axis.",
AttributeProto::INTS,
OPTIONAL)
.Attr("pads", pads_doc, AttributeProto::INTS, OPTIONAL)
.Input(
0,
"X",
"Input data tensor that has to be unpooled. "
"This tensor is typically the first output of the MaxPool op."
"Dimensions for image case are (N x C x H x W), "
"where N is the batch size, C is the number of "
"channels, and H and W are the height and the "
"width of the data. For non-image case, the "
"dimensions are in the form of "
"(N x C x D1 x D2 ... Dn), where N is the batch "
"size. Optionally, if dimension denotation is "
"in effect, the operation expects the input "
"data tensor to arrive with the dimension denotation "
"of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].",
"T1")
.Input(
1,
"I",
"Input data tensor containing the indices corresponding to "
"elements in the first input tensor X."
"This tensor is typically the second output of the MaxPool op."
"Dimensions must be the same as input tensor X. "
"The indices are linear, i.e. computed considering the tensor as flattened 1-D tensor, "
"assuming row-major storage. Also, the linear indices should not consider padding. "
"So the values in indices are in the range [0, N x C x D1 x ... x Dn).",
"T2")
.Input(
2,
"output_shape",
"The shape of the output can be explicitly set which will cause pads values to be auto generated. If 'output_shape' is specified, "
"'pads' values are ignored.",
"T2",
OpSchema::Optional)
.Output(
0,
"output",
"Output data tensor that contains the result of the unpooling.",
"T1")
.TypeConstraint(
"T1",
{"tensor(float16)", "tensor(float)", "tensor(double)"},
"Constrain input and output types to float tensors.")
.TypeConstraint(
"T2",
{"tensor(int64)"},
"Constrain index tensor to int64")
.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
maxUnpoolShapeInference(ctx);
}));
} // namespace ONNX_NAMESPACE
namespace ONNX_NAMESPACE {
std::function<void(OpSchema&)> LpPoolOpSchemaGenerator(const char* name) {
return [=](OpSchema& schema) {
std::string doc = R"DOC(
{name} consumes an input tensor X and applies Lp pooling across
the tensor according to kernel sizes, stride sizes, and pad lengths.
Lp pooling consisting of computing the Lp norm on all values of a subset
of the input tensor according to the kernel size and downsampling the
data into the output tensor Y for further processing.)DOC";
ReplaceAll(doc, "{name}", name);
schema.SetDoc(doc);
schema.Attr(
"kernel_shape",
"The size of the kernel along each axis.",
AttributeProto::INTS);
schema.Attr(
"strides", "Stride along each axis.", AttributeProto::INTS, OPTIONAL);
schema.Attr(
"auto_pad",
auto_pad_doc,
AttributeProto::STRING,
std::string("NOTSET"));
schema.Attr("pads", pads_doc, AttributeProto::INTS, OPTIONAL);
schema.Attr(
"p",
"p value of the Lp norm used to pool over the input data.",
AttributeProto::INT,
static_cast<int64_t>(2));
schema.Input(
0,
"X",
"Input data tensor from the previous operator; "
"dimensions for image case are (N x C x H x W), "
"where N is the batch size, C is the number of "
"channels, and H and W are the height and the "
"width of the data. For non image case, the "
"dimensions are in the form of "
"(N x C x D1 x D2 ... Dn), where N is the "
"batch size.",
"T");
schema.Output(
0,
"Y",
"Output data tensor from Lp pooling across the input "
"tensor. Dimensions will vary based on various kernel, stride, and pad "
"sizes.",
"T");
schema.TypeConstraint(
"T",
{"tensor(float16)", "tensor(float)", "tensor(double)"},
"Constrain input and output types to float tensors.");
schema.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
convPoolTypeAndShapeInference(ctx, false, true);
});
};
}
ONNX_OPERATOR_SET_SCHEMA(
LpPool,
2,
OpSchema().FillUsing(LpPoolOpSchemaGenerator("LpPool")));
} // namespace ONNX_NAMESPACE
// For ROI pool operations.
void roiPoolTypeShapeInference(InferenceContext& ctx) {
propagateElemTypeFromInputToOutput(ctx, 0, 0);
// rois is the second input.
if (!hasNInputShapes(ctx, 2)) {
return;
}
auto input_shape = ctx.getInputType(0)->tensor_type().shape();
auto rios_shape = ctx.getInputType(1)->tensor_type().shape();
if (input_shape.dim_size() < 2) {
fail_shape_inference("Input tensor must have at least 2 dimensions");
}
if (rios_shape.dim_size() != 2) {
fail_shape_inference("RoIs tensor must have 2 dimensions");
}
// first dim is the batch axis and the next is the number of channels.
size_t n_input_dims = static_cast<size_t>(input_shape.dim_size() - 2);
std::vector<int64_t> pooled_shape;
if (getRepeatedAttribute(ctx, "pooled_shape", pooled_shape)) {
if (pooled_shape.size() != n_input_dims) {
fail_shape_inference("Attribute pooled_shape has incorrect length");
}
} else {
fail_shape_inference("Attribute pooled_shape must be specified");
}
// (num_rois, channels, pooled_shape[0], pooled_shape[1])
auto output_shape =
ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
*output_shape->add_dim() = rios_shape.dim(0);
*output_shape->add_dim() = input_shape.dim(1);
output_shape->add_dim()->set_dim_value(pooled_shape[0]);
output_shape->add_dim()->set_dim_value(pooled_shape[1]);
}
namespace ONNX_NAMESPACE {
std::function<void(OpSchema&)> RoiPoolOpSchemaGenerator(const char* name) {
return [=](OpSchema& schema) {
std::string doc = R"DOC(
ROI {name} pool consumes an input tensor X and region of interests (RoIs) to
apply {name} pooling across each RoI, to produce output 4-D tensor of shape
(num_rois, channels, pooled_shape[0], pooled_shape[1]).)DOC";
ReplaceAll(doc, "{name}", name);
schema.SetDoc(doc);
schema.Attr(
"pooled_shape",
"ROI pool output shape (height, width).",
AttributeProto::INTS);
schema.Attr(
"spatial_scale",
"Multiplicative spatial scale factor to translate ROI coordinates from their input scale to the scale used when pooling.",
AttributeProto::FLOAT,
1.f);
schema.Input(
0,
"X",
"Input data tensor from the previous operator; "
"dimensions for image case are (N x C x H x W), "
"where N is the batch size, C is the number of "
"channels, and H and W are the height and the "
"width of the data.",
"T");
schema.Input(
1,
"rois",
"RoIs (Regions of Interest) to pool over. Should "
"be a 2-D tensor of shape (num_rois, 5) given as "
"[[batch_id, x1, y1, x2, y2], ...].",
"T");
schema.Output(
0,
"Y",
"RoI pooled output 4-D tensor of shape (num_rois, channels, pooled_shape[0], pooled_shape[1]).",
"T");
schema.TypeConstraint(
"T",
{"tensor(float16)", "tensor(float)", "tensor(double)"},
"Constrain input and output types to float tensors.");
schema.TypeAndShapeInferenceFunction(
[](InferenceContext& ctx) { roiPoolTypeShapeInference(ctx); });
};
}
ONNX_OPERATOR_SET_SCHEMA(
MaxRoiPool,
1,
OpSchema().FillUsing(RoiPoolOpSchemaGenerator("max")));
} // namespace ONNX_NAMESPACE
namespace ONNX_NAMESPACE {
std::function<void(OpSchema&)> ConvOpSchemaGenerator(const char* filter_desc) {
return [=](OpSchema& schema) {
std::string doc = R"DOC(
The convolution operator consumes an input tensor and {filter_desc}, and
computes the output.)DOC";
ReplaceAll(doc, "{filter_desc}", filter_desc);
schema.SetDoc(doc);
schema.Input(
0,
"X",
"Input data tensor from previous layer; "
"has size (N x C x H x W), where N is the batch size, "
"C is the number of channels, and H and W are the "
"height and width. Note that this is for the 2D image. "
"Otherwise the size is (N x C x D1 x D2 ... x Dn). "
"Optionally, if dimension denotation is "
"in effect, the operation expects input data tensor "
"to arrive with the dimension denotation of [DATA_BATCH, "
"DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].",
"T");
schema.Input(
1,
"W",
"The weight tensor that will be used in the "
"convolutions; has size (M x C/group x kH x kW), where C "
"is the number of channels, and kH and kW are the "
"height and width of the kernel, and M is the number "
"of feature maps. For more than 2 dimensions, the "
"kernel shape will be (M x C/group x k1 x k2 x ... x kn), "
"where (k1 x k2 x ... kn) is the dimension of the kernel. "
"Optionally, if dimension denotation is in effect, "
"the operation expects the weight tensor to arrive "
"with the dimension denotation of [FILTER_OUT_CHANNEL, "
"FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. "
"X.shape[1] == (W.shape[1] * group) == C "
"(assuming zero based indices for the shape array). "
"Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ",
"T");
schema.Input(
2,
"B",
"Optional 1D bias to be added to the convolution, has size of M.",
"T",
OpSchema::Optional);
schema.Output(
0,
"Y",
"Output data tensor that contains the result of the "
"convolution. The output dimensions are functions "
"of the kernel size, stride size, and pad lengths.",
"T");
schema.TypeConstraint(
"T",
{"tensor(float16)", "tensor(float)", "tensor(double)"},
"Constrain input and output types to float tensors.");
schema.Attr(
"kernel_shape",
"The shape of the convolution kernel. If not present, should be inferred from input W.",
AttributeProto::INTS,
OPTIONAL);
schema.Attr(
"dilations",
"dilation value along each axis of the filter.",
AttributeProto::INTS,
OPTIONAL);
schema.Attr(
"strides", "Stride along each axis.", AttributeProto::INTS, OPTIONAL);
schema.Attr(
"auto_pad",
auto_pad_doc,
AttributeProto::STRING,
std::string("NOTSET"));
schema.Attr("pads", pads_doc, AttributeProto::INTS, OPTIONAL);
schema.Attr(
"group",
"number of groups input channels and output channels are divided into.",
AttributeProto::INT,
static_cast<int64_t>(1));
schema.TypeAndShapeInferenceFunction([](InferenceContext& ctx) {
convPoolTypeAndShapeInference(ctx, true, false);
});
};
}
ONNX_OPERATOR_SET_SCHEMA(
Conv,
1,
OpSchema().FillUsing(ConvOpSchemaGenerator("a filter")));
} // namespace ONNX_NAMESPACE
void convTransposeShapeInference(InferenceContext& ctx) {
propagateElemTypeFromInputToOutput(ctx, 0, 0);
// we need at least two inputs to have a shape for this inference.
if (!hasNInputShapes(ctx, 2)) {
return;
}
// don't bother with legacy auto_pad for now
const auto* auto_pad_attr = ctx.getAttribute("auto_pad");
if ((nullptr != auto_pad_attr) && (auto_pad_attr->s() != "NOTSET")) {
return;
}
int64_t group = getAttribute(ctx, "group", 1);
auto input_shape = ctx.getInputType(0)->tensor_type().shape();
if (input_shape.dim_size() < 2) {
return; // Input tensor should have at least two dimensions.
}
// first dim is the batch axis and the next is the number of channels.
size_t n_input_dims = static_cast<size_t>(input_shape.dim_size() - 2);
std::vector<int64_t> dilations;
if (getRepeatedAttribute(ctx, "dilations", dilations)) {
for (auto i : dilations) {
if (i != 1)
return; // we don't handle dialations not 1.
}
}
std::vector<int64_t> pads;
if (getRepeatedAttribute(ctx, "pads", pads)) {
if (pads.size() != n_input_dims * 2) {
return;
}
} else {
pads.assign(n_input_dims * 2, 0);
}
std::vector<int64_t> strides;
if (getRepeatedAttribute(ctx, "strides", strides)) {
if (strides.size() != n_input_dims) {
return;
}
} else {
strides.assign(n_input_dims, 1);
}
std::vector<int64_t> kernel_shape;
if (getRepeatedAttribute(ctx, "kernel_shape", kernel_shape)) {
if (kernel_shape.size() != n_input_dims) {
return;
}
} else {
auto second_input_shape = ctx.getInputType(1)->tensor_type().shape();
for (int i = 2; i < second_input_shape.dim_size(); ++i) {
if (!second_input_shape.dim(i).has_dim_value()) {
return;
}
kernel_shape.push_back(second_input_shape.dim(i).dim_value());
}
}
std::vector<int64_t> output_shape;
bool output_shape_presented = true;
if (getRepeatedAttribute(ctx, "output_shape", output_shape)) {
if (output_shape.size() != n_input_dims) {
return;
}
} else {
output_shape_presented = false;
}
std::vector<int64_t> output_padding;
if (getRepeatedAttribute(ctx, "output_padding", output_padding)) {
if (output_padding.size() != n_input_dims) { // Added only to one side.
return;
}
} else {
output_padding.assign(n_input_dims, 0);
}
auto final_output_shape =
ctx.getOutputType(0)->mutable_tensor_type()->mutable_shape();
*final_output_shape->add_dim() = input_shape.dim(0);
*final_output_shape->add_dim() =
ctx.getInputType(1)->tensor_type().shape().dim(1) *
group; // channels should be the second dim of second input multiply
// group.
int size_of_output;
if (output_shape_presented) {
size_of_output = static_cast<int>(output_shape.size());
for (int i = 0; i < size_of_output; ++i) {
if (input_shape.dim(i + 2).has_dim_value()) {
if (output_shape[i] < input_shape.dim(i + 2).dim_value()) {
// TODO: throw exception?
return; // output shape value cannot be smaller than the input shape
// value
}
}
final_output_shape->add_dim()->set_dim_value(output_shape[i]);
}
return;
} else {
size_of_output = input_shape.dim_size() - 2;
for (int i = 0; i < size_of_output; ++i) {
if (input_shape.dim(i + 2).has_dim_value()) {
int64_t output_shape_dim =
strides[i] * (input_shape.dim(i + 2).dim_value() - 1) +
output_padding[i] + kernel_shape[i] - pads[i] -
pads[i + n_input_dims];
final_output_shape->add_dim()->set_dim_value(output_shape_dim);
} else {
final_output_shape->add_dim();
}
}
return;
}
}