forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.cc
1871 lines (1687 loc) · 61.7 KB
/
backend.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
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/onnx/backend.h"
#include "caffe2/onnx/device.h"
#include "caffe2/onnx/helper.h"
#include "caffe2/utils/map_utils.h"
#include "caffe2/utils/proto_utils.h"
#ifndef C10_MOBILE
#include "onnx/checker.h"
#include "onnx/optimizer/optimize.h"
#endif
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include <cmath>
#include <iostream>
#include <limits>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
namespace caffe2 {
namespace onnx {
namespace {
bool AlmostEqual(double a, double b) {
constexpr static double kEps = 1e-15;
return (fabs(a - b) < kEps);
}
template <class T>
bool TryConvertingTensorRawValues(
const TensorProto& onnx_tensor,
::google::protobuf::RepeatedField<T>* field) {
if (!onnx_tensor.has_raw_data()) {
return false;
}
size_t raw_size = onnx_tensor.raw_data().size();
CAFFE_ENFORCE_EQ(raw_size % sizeof(T), 0);
size_t num_elements = raw_size / sizeof(T);
const void* src_ptr = static_cast<const void*>(onnx_tensor.raw_data().data());
field->Resize(num_elements, 0);
void* target_ptr = static_cast<void*>(field->mutable_data());
memcpy(target_ptr, src_ptr, raw_size);
return true;
}
bool IsOperator(const std::string& op_type) {
// pull in all the operators upon first invocation
// Intentional leaky
static std::set<std::string>* ops_ =
new std::set<std::string>(caffe2::GetRegisteredOperators());
return ops_->count(caffe2::OpRegistryKey(op_type, "DEFAULT"));
}
caffe2::DeviceOption GetDeviceOption(const Device& onnx_device) {
static const std::unordered_map<DeviceType, caffe2::DeviceType> m = {
{DeviceType::CPU, caffe2::DeviceType::CPU},
{DeviceType::CUDA, caffe2::DeviceType::CUDA}};
caffe2::DeviceOption d;
d.set_device_type(static_cast<int32_t>(m.at(onnx_device.type)));
d.set_device_id(onnx_device.device_id);
return d;
}
#ifndef C10_MOBILE
ModelProto OptimizeOnnx(const ModelProto& input, bool init) {
std::vector<std::string> passes{"fuse_consecutive_transposes",
"eliminate_nop_transpose",
"fuse_transpose_into_gemm"};
if (init) {
passes.emplace_back("split_init");
} else {
passes.emplace_back("split_predict");
}
return ::ONNX_NAMESPACE::optimization::Optimize(input, passes);
}
#endif
template <class T, class U>
U LookUpWithDefault(
const std::unordered_map<T, U>& map,
const T& key,
const U& default_value) {
const auto it = map.find(key);
if (it == map.end()) {
return default_value;
} else {
return it->second;
}
}
void UpdateNames(std::shared_ptr<DummyName> dummy, const caffe2::OperatorDef& op) {
for (const auto& n : op.input()) {
dummy->AddName(n);
}
for (const auto& n : op.output()) {
dummy->AddName(n);
}
}
void BuildOperator(
caffe2::OperatorDef* c2_op,
const std::string& op_type,
const std::vector<std::string>& inputs,
const std::vector<std::string>& outputs,
const std::vector<caffe2::Argument>& args) {
c2_op->set_name("");
c2_op->set_type(op_type);
for (const auto& input : inputs) {
c2_op->add_input(input);
}
for (const auto& output : outputs) {
c2_op->add_output(output);
}
for (const auto& arg : args) {
auto* tmp = c2_op->add_arg();
tmp->CopyFrom(arg);
}
}
void BuildOperator(
caffe2::OperatorDef* c2_op,
const std::string& op_type,
const std::vector<std::string>& inputs,
const std::vector<std::string>& outputs) {
std::vector<caffe2::Argument> empty;
BuildOperator(c2_op, op_type, inputs, outputs, empty);
}
void CopyOnnxAttrValueToCaffe2Arg(
caffe2::Argument* arg,
const AttributeProto& attr) {
if (attr.has_f()) {
arg->set_f(attr.f());
} else if (attr.has_i()) {
arg->set_i(attr.i());
} else if (attr.has_s()) {
arg->set_s(attr.s());
} else if (attr.has_t()) {
// For proto, we convert it to serialized string
std::string buffer;
attr.t().SerializeToString(&buffer);
arg->set_s(buffer);
} else if (attr.floats_size()) {
arg->mutable_floats()->CopyFrom(attr.floats());
} else if (attr.ints_size()) {
arg->mutable_ints()->CopyFrom(attr.ints());
} else if (attr.strings_size()) {
arg->mutable_strings()->CopyFrom(attr.strings());
} else {
CAFFE_THROW("Unsupported ONNX attribute: ", attr.name());
}
}
} // namespace
OnnxAttributes::OnnxAttributes(const NodeProto& node) {
for (const auto& attr : node.attribute()) {
onnx_attrs_.emplace(attr.name(), &attr);
}
}
template <>
int64_t OnnxAttributes::get(const std::string& key) const {
int64_t value = 0;
const auto it = onnx_attrs_.find(key);
if (it != onnx_attrs_.end()) {
const AttributeProto& attr = *it->second;
value = attr.i();
}
return value;
}
template <>
float OnnxAttributes::get(const std::string& key) const {
float value = 0.0;
const auto it = onnx_attrs_.find(key);
if (it != onnx_attrs_.end()) {
const AttributeProto& attr = *it->second;
value = attr.f();
}
return value;
}
template <>
::google::protobuf::RepeatedPtrField<std::string> OnnxAttributes::get(
const std::string& key) const {
::google::protobuf::RepeatedPtrField<std::string> value;
const auto it = onnx_attrs_.find(key);
if (it != onnx_attrs_.end()) {
const AttributeProto& attr = *it->second;
value.CopyFrom(attr.strings());
}
return value;
}
template <>
::google::protobuf::RepeatedField<::google::protobuf::int64>
OnnxAttributes::get(const std::string& key) const {
::google::protobuf::RepeatedField<::google::protobuf::int64> value;
const auto it = onnx_attrs_.find(key);
if (it != onnx_attrs_.end()) {
const AttributeProto& attr = *it->second;
value.CopyFrom(attr.ints());
}
return value;
}
template <>
::google::protobuf::RepeatedField<float>
OnnxAttributes::get(const std::string& key) const {
::google::protobuf::RepeatedField<float> value;
const auto it = onnx_attrs_.find(key);
if (it != onnx_attrs_.end()) {
const AttributeProto& attr = *it->second;
value.CopyFrom(attr.floats());
}
return value;
}
template <>
const TensorProto* OnnxAttributes::get(const std::string& key) const {
const TensorProto* value = nullptr;
const auto it = onnx_attrs_.find(key);
if (it != onnx_attrs_.end()) {
const AttributeProto& attr = *it->second;
value = &attr.t();
}
return value;
}
::google::protobuf::RepeatedPtrField<caffe2::Argument>
OnnxAttributes::OnnxAttrToCaffe2Arg(
std::function<std::string(const std::string&)> mapper) const {
::google::protobuf::RepeatedPtrField<caffe2::Argument> args;
for (const auto& kv : onnx_attrs_) {
// If the attribute was rewritten, we use it instead. Note that the
// rewritten attribute still has the unmapped name
const auto& attr = rewritten_onnx_attrs_.count(kv.first)
? rewritten_onnx_attrs_.at(kv.first)
: (*kv.second);
auto* arg = args.Add();
arg->set_name(mapper(attr.name()));
CopyOnnxAttrValueToCaffe2Arg(arg, attr);
}
for (const auto& kv : rewritten_onnx_attrs_) {
// If rewritten attribute doesn't appear in the original attributes, this is
// a newlly added one and we need to add this to argument too
if (!onnx_attrs_.count(kv.first)) {
const auto& attr = kv.second;
auto* arg = args.Add();
arg->set_name(mapper(attr.name()));
CopyOnnxAttrValueToCaffe2Arg(arg, attr);
}
}
return args;
}
const std::unordered_map<std::string, int>&
Caffe2Backend::get_broken_operators() const {
const static std::unordered_map<std::string, int> kBrokenOperators{};
return kBrokenOperators;
}
// Temporary hack for RNN related operators, as we don't have C++ interface in
// C2 to build those operators yet
const std::unordered_set<std::string>& Caffe2Backend::get_rnn_operators()
const {
const static std::unordered_set<std::string> kRNNOperators{
"LSTM", "GRU", "RNN"};
return kRNNOperators;
}
// Operators that are different between Caffe2 and
// ONNX but only in their name.
// In most cases, this should be empty - as the effort of ONNX is
// to unify the operator definitions.
const std::unordered_map<std::string, std::string>&
Caffe2Backend::get_renamed_operators() const {
const static std::unordered_map<std::string, std::string> kRenamedOperators{
{"Caffe2ConvTranspose", "ConvTranspose"},
{"GlobalMaxPool", "MaxPool"},
{"GlobalAveragePool", "AveragePool"},
{"Pad", "PadImage"},
{"Neg", "Negative"},
{"BatchNormalization", "SpatialBN"},
{"InstanceNormalization", "InstanceNorm"},
{"MatMul", "BatchMatMul"},
{"Upsample", "ResizeNearest"},
{"Identity", "Copy"},
{"InstanceNormalization", "InstanceNorm"},
{"Equal", "EQ"},
{"Less", "LT"},
{"Greater", "GT"},
{"Unsqueeze", "ExpandDims"},
{"Tile", "NumpyTile"},
{"DynamicSlice", "Slice"},
{"ConstantOfShape", "ConstantFill"},
{"RandomNormal", "GaussianFill"},
{"RandomNormalLike", "GaussianFill"}};
return kRenamedOperators;
}
const std::unordered_map<std::string, std::string>&
Caffe2Backend::get_renamed_attrs() const {
const static std::unordered_map<std::string, std::string> kRenamedAttrs{
{"kernel_shape", "kernels"}};
return kRenamedAttrs;
}
const std::
unordered_map<std::string, std::unordered_map<std::string, std::string>>&
Caffe2Backend::get_per_op_renamed_attrs() const {
const static std::
unordered_map<std::string, std::unordered_map<std::string, std::string>>
kPerOpRenamedAttrs = {{"Squeeze", {{"axes", "dims"}}},
{"Unsqueeze", {{"axes", "dims"}}},
{"Transpose", {{"perm", "axes"}}},
{"ConvTranspose", {{"output_padding", "adjs"}}},
{"Selu", {{"gamma", "scale"}}}};
return kPerOpRenamedAttrs;
}
// operators whose behavior is different beyond renaming
// the value is an attribute of this class that is a
// function from ToffeIR node_def to caffe2 op_def
const std::unordered_map<std::string, Caffe2Backend::SpecialOpConverter>&
Caffe2Backend::get_special_operators() const {
const static std::
unordered_map<std::string, Caffe2Backend::SpecialOpConverter>
kSpecialOperators = {
{"ArgMax", &Caffe2Backend::CreateArgMaxMin},
{"ArgMin", &Caffe2Backend::CreateArgMaxMin},
{"Cast", &Caffe2Backend::CreateCast},
{"Constant", &Caffe2Backend::CreateConstant},
{"ConstantOfShape", &Caffe2Backend::CreateConstantOfShape},
{"Conv", &Caffe2Backend::CreateConvPoolOpBase},
{"AveragePool", &Caffe2Backend::CreateConvPoolOpBase},
{"GlobalAveragePool", &Caffe2Backend::CreateConvPoolOpBase},
{"GlobalMaxPool", &Caffe2Backend::CreateConvPoolOpBase},
{"MaxPool", &Caffe2Backend::CreateConvPoolOpBase},
{"Reshape", &Caffe2Backend::CreateReshape},
{"Int8Reshape", &Caffe2Backend::CreateReshape},
{"Gather", &Caffe2Backend::CreateGather},
{"Gemm", &Caffe2Backend::CreateGemm},
{"Pad", &Caffe2Backend::CreatePad},
{"Concat", &Caffe2Backend::CreateConcat},
{"Int8Concat", &Caffe2Backend::CreateConcat},
{"LogSoftmax", &Caffe2Backend::CreateLogSoftmax},
{"Slice", &Caffe2Backend::CreateSlice},
{"Split", &Caffe2Backend::CreateSplit},
{"Reciprocal", &Caffe2Backend::CreateReciprocal},
{"BatchNormalization", &Caffe2Backend::CreateBatchNormalization},
{"MatMul", &Caffe2Backend::CreateMatMul},
{"Upsample", &Caffe2Backend::CreateUpsample},
{"Dropout", &Caffe2Backend::CreateDropout},
{"LRN", &Caffe2Backend::CreateLRN},
{"DynamicSlice", &Caffe2Backend::CreateDynamicSlice},
{"RandomNormal", &Caffe2Backend::CreateRandomNormal},
{"RandomNormalLike", &Caffe2Backend::CreateRandomNormal},
{"Where", &Caffe2Backend::CreateWhereOp},
{"NonZero", &Caffe2Backend::CreateNonZeroOp},
{"Multinomial", &Caffe2Backend::CreateMultinomialOp}};
return kSpecialOperators;
}
//============================
// Special Operator Converters
//============================
Caffe2Ops Caffe2Backend::CreateArgMaxMin(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
auto& attributes = onnx_node->attributes;
if (!attributes.HasAttribute("axis")) {
auto* attr = attributes.AddRewrittenAttribute("axis");
attr->set_i(0);
}
return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
}
Caffe2Ops Caffe2Backend::CreateCast(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
auto onnx_dtype =
onnx_node->attributes.get<int64_t>("to", TensorProto::UNDEFINED);
auto c2_dtype = caffe2::TensorProto::UNDEFINED;
switch (onnx_dtype) {
case ::ONNX_NAMESPACE::TensorProto::FLOAT:
c2_dtype = caffe2::TensorProto::FLOAT;
break;
case ::ONNX_NAMESPACE::TensorProto::UINT8:
c2_dtype = caffe2::TensorProto::UINT8;
break;
case ::ONNX_NAMESPACE::TensorProto::INT8:
c2_dtype = caffe2::TensorProto::INT8;
break;
case ::ONNX_NAMESPACE::TensorProto::UINT16:
c2_dtype = caffe2::TensorProto::UINT16;
break;
case ::ONNX_NAMESPACE::TensorProto::INT16:
c2_dtype = caffe2::TensorProto::INT16;
break;
case ::ONNX_NAMESPACE::TensorProto::INT32:
c2_dtype = caffe2::TensorProto::INT32;
break;
case ::ONNX_NAMESPACE::TensorProto::INT64:
c2_dtype = caffe2::TensorProto::INT64;
break;
case ::ONNX_NAMESPACE::TensorProto::STRING:
c2_dtype = caffe2::TensorProto::STRING;
break;
case ::ONNX_NAMESPACE::TensorProto::BOOL:
c2_dtype = caffe2::TensorProto::BOOL;
break;
case ::ONNX_NAMESPACE::TensorProto::FLOAT16:
c2_dtype = caffe2::TensorProto::FLOAT16;
break;
case ::ONNX_NAMESPACE::TensorProto::DOUBLE:
c2_dtype = caffe2::TensorProto::DOUBLE;
break;
case ::ONNX_NAMESPACE::TensorProto::UINT32:
case ::ONNX_NAMESPACE::TensorProto::UINT64:
case ::ONNX_NAMESPACE::TensorProto::COMPLEX64:
case ::ONNX_NAMESPACE::TensorProto::COMPLEX128:
case ::ONNX_NAMESPACE::TensorProto::UNDEFINED:
c2_dtype = caffe2::TensorProto::UNDEFINED;
break;
};
CAFFE_ENFORCE_NE(
c2_dtype,
caffe2::TensorProto::UNDEFINED,
"Casting to '",
onnx_dtype,
"' dtype is not supported");
CAFFE_ENFORCE_EQ(
c2_op.ops.Get(0).arg().size(),
1,
"Unexpected number of attributes in 'Cast'");
c2_op.ops.Mutable(0)->mutable_arg(0)->set_i(c2_dtype);
return c2_op;
}
Caffe2Ops Caffe2Backend::CreateConstant(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
CAFFE_ENFORCE_EQ(onnx_node->node.output_size(), 1);
Caffe2Ops ret;
auto* c2_op = ret.ops.Add();
const auto* value = onnx_node->attributes.get<const TensorProto*>("value");
BuildTensorFillingOp(c2_op, *value, onnx_node->node.output(0));
return ret;
}
Caffe2Ops Caffe2Backend::CreateConstantOfShape(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
CAFFE_ENFORCE_EQ(onnx_node->node.input_size(), 1);
CAFFE_ENFORCE_EQ(onnx_node->node.output_size(), 1);
Caffe2Ops ret;
auto* c2_op = ret.ops.Add();
const auto* value = onnx_node->attributes.get<const TensorProto*>("value");
if (value) {
BuildTensorFillingOp(c2_op, *value, onnx_node->node.output(0), onnx_node->node.input(0));
} else {
c2_op->set_type("ConstantFill");
c2_op->add_input(onnx_node->node.input(0));
c2_op->add_output(onnx_node->node.output(0));
auto c2_input_as_shape = c2_op->add_arg();
c2_input_as_shape->set_name("input_as_shape");
c2_input_as_shape->set_i(1);
}
return ret;
}
// Note [Caffe2 ConvPoolOpBase]
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// To understand what is going on here, we have to talk a little bit about
// Caffe2's internals.
//
// First, it's important to know that all of Caffe2's pooling and convolution
// operators inherit from "ConvPoolOpBase", which is an abstract class that
// defines all of the attributes (kernels, dilations, strides, etc) which one
// sees on these operators. Unfortunately, Caffe2's documentation generator
// doesn't know how to handle cases like this, so for example, if you look at
// the docs for MaxPool at
// <https://caffe2.ai/docs/operators-catalogue.html#maxpool> you won't see any
// of the attributes. You have to go source diving to find the information; in
// particular, you want to look at:
// https://github.com/caffe2/caffe2/blob/master/caffe2/operators/conv_pool_op_base.h
// This class handles *global* pooling as well.
//
// Second, it's important to know what Caffe2 expects for padding, which can
// be somewhat difficult to understand from the code because Caffe2 handles
// both singular/pluralized spellings of padding, and there is also legacy
// padding business. The short version of the story is that, for NON-legacy
// padding (which is what we want to output), padding is expected to be
// *twice* the size of kernels. So if you have a 2D convolution, Caffe2
// will accept two values in 'kernels', but FOUR values in 'pads';
// furthermore, this is *mandatory.*
//
// Finally, ConvPoolOpBase is not the only class of it's kind; there is
// be tricked by the fact that Conv and ConvTranspose have similar
// parameters; they exercise different codepaths and need to be handled
// differently.
Caffe2Ops Caffe2Backend::CreateConvPoolOpBase(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
const auto& node = onnx_node->node;
auto& attributes = onnx_node->attributes;
if (node.op_type().find("Global") == 0) {
auto* attr = attributes.AddRewrittenAttribute("global_pooling");
attr->set_i(1);
}
if (attributes.HasAttribute("kernel_shape") &&
attributes.HasAttribute("pads")) {
auto kernel_shape =
attributes
.get<::google::protobuf::RepeatedField<::google::protobuf::int64>>(
"kernel_shape");
auto pads =
attributes
.get<::google::protobuf::RepeatedField<::google::protobuf::int64>>(
"pads");
if (kernel_shape.size() == pads.size()) {
// Caffe2 requires pads to be twice the size of kernels.
auto* attr = attributes.AddRewrittenAttribute("pads");
attr->mutable_ints()->CopyFrom(pads);
attr->mutable_ints()->MergeFrom(pads);
}
}
return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
}
Caffe2Ops Caffe2Backend::CreateReshape(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
CAFFE_ENFORCE_EQ(c2_op.ops.size(), 1);
auto* op = c2_op.ops.Mutable(0);
op->add_output(dummy_->NewDummyName());
return c2_op;
}
Caffe2Ops Caffe2Backend::CreateRandomNormal(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
auto& attributes = onnx_node->attributes;
if (attributes.HasAttribute("seed")) {
CAFFE_THROW("Caffe2 GaussianFill does not support random seed");
}
if (attributes.HasAttribute("dtype")) {
if (attributes.get<int64_t>("dtype") != TensorProto::FLOAT) {
CAFFE_THROW("Caffe2 GaussianFill only support FLOAT dtype");
}
attributes.remove("dtype");
}
if (attributes.HasAttribute("scale")) {
auto scale = attributes.get<float>("scale");
auto* attr = attributes.AddRewrittenAttribute("std");
attr->set_f(scale);
attributes.remove("scale");
}
return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
}
Caffe2Ops Caffe2Backend::CreateWhereOp(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
// The native Caffe2 op doesn't support broadcasting, so we defer the handling
// of this op to the ATen library that does.
onnx::NodeProto converted;
converted.CopyFrom(onnx_node->node);
converted.set_op_type("ATen");
onnx::AttributeProto* attr = converted.add_attribute();
attr->set_name("operator");
attr->set_s("where");
OnnxNode new_node(converted);
return CommonOnnxNodeToCaffe2Ops(&new_node, ctx);
}
Caffe2Ops Caffe2Backend::CreateNonZeroOp(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
// Native Caffe2 doesn't support NonZero, fallback to ATen.
// ATen nonzero is equivalent to Transpose(ONNX::NonZero).
onnx::NodeProto converted;
converted.CopyFrom(onnx_node->node);
auto nonzero_output = dummy_->NewDummyName();
converted.set_output(0, nonzero_output);
converted.set_op_type("ATen");
onnx::AttributeProto* attr = converted.add_attribute();
attr->set_name("operator");
attr->set_s("nonzero");
OnnxNode new_node(converted);
auto ret = CommonOnnxNodeToCaffe2Ops(&new_node, ctx);
auto* c2_transpose = ret.ops.Add();
BuildOperator(c2_transpose, "Transpose", {nonzero_output}, {onnx_node->node.output(0)});
return ret;
}
Caffe2Ops Caffe2Backend::CreateMultinomialOp(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
// Fallback to ATen.
// ATen::Multinomial takes probabilities as input, ONNX Multinomial expects input to be log probabilities.
Caffe2Ops ret;
auto c2_exp_output = dummy_->NewDummyName();
auto* c2_exp = ret.ops.Add();
BuildOperator(c2_exp, "Exp", {onnx_node->node.input(0)}, {c2_exp_output});
auto* c2_multinomial = ret.ops.Add();
caffe2::Argument c2_arg_op;
c2_arg_op.set_name("operator");
c2_arg_op.set_s("multinomial");
// ONNX Multinomial only supports replacement=True.
caffe2::Argument c2_arg_rep;
c2_arg_rep.set_name("replacement");
c2_arg_rep.set_i(1);
auto& onnx_attributes = onnx_node->attributes;
caffe2::Argument c2_arg_num;
c2_arg_num.set_name("num_samples");
c2_arg_num.set_i(onnx_attributes.get<int64_t>("sample_size"));
// ONNX Multinomial has attribute dtype in {int64, int32}, which specifies output datatype.
// ATen::Multinomial output dtype is always int64.
auto onnx_dtype =
onnx_attributes.get<int64_t>("dtype", TensorProto::UNDEFINED);
if (onnx_dtype == ::ONNX_NAMESPACE::TensorProto::INT64) {
BuildOperator(
c2_multinomial,
"ATen",
{c2_exp_output},
{onnx_node->node.output(0)},
{c2_arg_op, c2_arg_rep, c2_arg_num});
} else if (onnx_dtype == ::ONNX_NAMESPACE::TensorProto::INT32) {
auto c2_multinomial_output = dummy_->NewDummyName();
BuildOperator(
c2_multinomial,
"ATen",
{c2_exp_output},
{c2_multinomial_output},
{c2_arg_op, c2_arg_rep, c2_arg_num});
auto* c2_cast = ret.ops.Add();
caffe2::Argument to;
to.set_name("to");
to.set_i(caffe2::TensorProto::INT32);
BuildOperator(c2_cast, "Cast", {c2_multinomial_output}, {onnx_node->node.output(0)}, {to});
} else {
CAFFE_THROW("ONNX does not support dtype other than int32/int64 in Multinomial, but get ", onnx_dtype);
}
return ret;
}
Caffe2Ops Caffe2Backend::CreateReciprocal(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
const auto& node = onnx_node->node;
if (node.input_size() != 1 || node.output_size() != 1) {
CAFFE_THROW("Caffe2 Reciprocal should have 1 input and 1 output");
}
Caffe2Ops ret;
auto* c2_op = ret.ops.Add();
caffe2::Argument exponent;
exponent.set_name("exponent");
exponent.set_f(-1.0);
BuildOperator(c2_op, "Pow", {node.input(0)}, {node.output(0)}, {exponent});
return ret;
}
Caffe2Ops Caffe2Backend::CreateGather(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
const auto& node = onnx_node->node;
if (node.input_size() < 2 || node.output_size() < 1) {
CAFFE_THROW("Caffe2 Gather should have 2 inputs and 1 output");
}
Caffe2Ops ret;
auto* c2_op = ret.ops.Add();
std::vector<std::string> inputs;
inputs.emplace_back(node.input(0));
inputs.emplace_back(node.input(1));
std::vector<std::string> outputs;
outputs.emplace_back(node.output(0));
auto axis = onnx_node->attributes.get<int64_t>("axis", 0L);
if (axis == 0) {
BuildOperator(c2_op, "Gather", inputs, outputs);
} else if (axis == 1) {
BuildOperator(c2_op, "BatchGather", inputs, outputs);
} else {
CAFFE_THROW(
"Caffe2 only supports Gather with axis being 0 or 1, ",
"whereas axis is ",
axis);
}
return ret;
}
Caffe2Ops Caffe2Backend::CreateGemm(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
const auto& node = onnx_node->node;
if (node.input_size() < 3 || node.output_size() < 1) {
CAFFE_THROW("Caffe2 Gemm should have 3 inputs and 1 output");
}
Caffe2Ops ret;
auto input_a = node.input(0);
auto input_b = node.input(1);
auto input_c = node.input(2);
auto output = node.output(0);
auto alpha = onnx_node->attributes.get<float>("alpha", 1.0);
auto beta = onnx_node->attributes.get<float>("beta", 1.0);
if (!AlmostEqual(alpha, 1)) {
auto scaled_a = dummy_->NewDummyName();
caffe2::Argument scale;
scale.set_name("scale");
scale.set_f(alpha);
auto* c2_op = ret.ops.Add();
BuildOperator(c2_op, "Scale", {input_a}, {scaled_a}, {scale});
input_a = scaled_a;
}
if (!AlmostEqual(beta, 1)) {
auto scaled_c = dummy_->NewDummyName();
caffe2::Argument scale;
scale.set_name("scale");
scale.set_f(beta);
auto* c2_op = ret.ops.Add();
BuildOperator(c2_op, "Scale", {input_c}, {scaled_c}, {scale});
input_c = scaled_c;
}
auto trans_a = onnx_node->attributes.get<int64_t>("transA", 0L);
auto trans_b = onnx_node->attributes.get<int64_t>("transB", 0L);
// Support broadcast by default when opset_version > 6.
auto broadcast =
onnx_node->attributes.get<int64_t>("broadcast",
(ctx.opset_version() > 6) ? 1L : 0L);
// If the c's shape information is available and c is a 1d tensor(except
// c is a scalar), use FC aggressively.
auto check_fc = [&]() -> bool {
const auto input_c_vi_iter = ctx.value_infos().find(node.input(2));
if (input_c_vi_iter == ctx.value_infos().end()) {
return false;
}
const auto input_c_shape =
input_c_vi_iter->second.type().tensor_type().shape();
if (input_c_shape.dim_size() != 1) {
return false;
}
// c is a scalar.
if (input_c_shape.dim(0).dim_value() == 1) {
const auto input_b_vi_iter = ctx.value_infos().find(node.input(1));
// If the b's shape is not available, skip FC.
if (input_b_vi_iter == ctx.value_infos().end()) {
return false;
}
const auto input_b_shape =
input_b_vi_iter->second.type().tensor_type().shape();
int input_b_last_dim_index = (trans_b) ? 0 : 1;
// If b's last dim is not 1, skip FC.
if (input_b_shape.dim_size() <= input_b_last_dim_index ||
input_b_shape.dim(input_b_last_dim_index).dim_value() != 1) {
return false;
}
}
return true;
};
if (!trans_a && broadcast && check_fc()) {
auto* c2_op = ret.ops.Add();
if (trans_b) {
BuildOperator(c2_op, "FC", {input_a, input_b, input_c}, {output});
} else {
BuildOperator(c2_op, "FCTransposed", {input_a, input_b, input_c}, {output});
}
} else {
auto ab = dummy_->NewDummyName();
caffe2::Argument arg_trans_a;
arg_trans_a.set_name("trans_a");
arg_trans_a.set_i(trans_a);
caffe2::Argument arg_trans_b;
arg_trans_b.set_name("trans_b");
arg_trans_b.set_i(trans_b);
auto* c2_op = ret.ops.Add();
BuildOperator(
c2_op, "MatMul", {input_a, input_b}, {ab}, {arg_trans_a, arg_trans_b});
c2_op = ret.ops.Add();
if (ctx.opset_version() >= 7) {
BuildOperator(c2_op, "Add", {ab, input_c}, {output});
} else {
caffe2::Argument arg_broadcast;
arg_broadcast.set_name("broadcast");
arg_broadcast.set_i(broadcast);
BuildOperator(c2_op, "Add", {ab, input_c}, {output}, {arg_broadcast});
}
}
return ret;
}
Caffe2Ops Caffe2Backend::CreatePad(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
auto& attributes = onnx_node->attributes;
::google::protobuf::RepeatedField<::google::protobuf::int64> pads;
std::string pad_name = ctx.opset_version() < 2 ? "paddings" : "pads";
pads = attributes
.get<::google::protobuf::RepeatedField<::google::protobuf::int64>>(
pad_name);
std::string str;
std::stringstream ss;
ss << "[";
for (const auto& i : pads) {
ss << i << ", ";
}
ss << "]";
str = ss.str();
// Guard the invalid (negative) pads attribute.
for (const auto i : pads) {
if (i < 0) {
CAFFE_THROW("ONNX does not support negative pads in Pad, but get ", str);
}
}
// first two dim is for batch and channel. Note that now all the values are
// non-negative
if (!(pads.size() == 8 &&
(pads.Get(0) + pads.Get(1) + pads.Get(4) + pads.Get(5) == 0))) {
CAFFE_THROW(
"Caffe2 only supports padding 2D Tensor, whereas padding is ", str);
}
// rewrite the padding info
auto* attr = attributes.AddRewrittenAttribute(pad_name);
attr->add_ints(pads.Get(2));
attr->add_ints(pads.Get(3));
attr->add_ints(pads.Get(6));
attr->add_ints(pads.Get(7));
return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
}
// TODO: Caffe2 Concat has an extra output. It should be only
// used when doing training, so we should change Caffe2 to allow
// 1 output.
Caffe2Ops Caffe2Backend::CreateConcat(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
CAFFE_ENFORCE_EQ(c2_op.ops.size(), 1);
auto* op = c2_op.ops.Mutable(0);
op->add_output(dummy_->NewDummyName());
return c2_op;
}
Caffe2Ops Caffe2Backend::CreateLogSoftmax(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
const auto& node = onnx_node->node;
if (node.input_size() < 1 || node.output_size() < 1) {
CAFFE_THROW("LogSoftmax should have 1 input and 1 output");
}
auto axis = onnx_node->attributes.get<int64_t>("axis", 1L);
caffe2::Argument arg_axis;
arg_axis.set_name("axis");
arg_axis.set_i(axis);
auto softmax_a = dummy_->NewDummyName();
Caffe2Ops ret;
auto* c2_op = ret.ops.Add();
BuildOperator(c2_op, "Softmax", {node.input(0)}, {softmax_a}, {arg_axis});
c2_op = ret.ops.Add();
BuildOperator(c2_op, "Log", {softmax_a}, {node.output(0)});
return ret;
}
Caffe2Ops Caffe2Backend::CreateSlice(
OnnxNode* onnx_node,
const ConversionContext& ctx) {
auto op_tmp = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx);
CAFFE_ENFORCE_EQ(op_tmp.ops.size(), 1);
auto* op = op_tmp.ops.Mutable(0);
std::unordered_map<std::string, caffe2::Argument*> args;
for (auto& arg : *op->mutable_arg()) {
args.emplace(arg.name(), &arg);
}
caffe2::Argument starts_vals;
starts_vals.set_name("values");
auto pos = args.find("starts");
if (pos != args.end()) {
for (auto i : pos->second->ints()) {
starts_vals.add_ints(i < 0 ? i - 1 : i);
}
args.erase(pos);
}
caffe2::Argument ends_vals;
ends_vals.set_name("values");
pos = args.find("ends");
if (pos != args.end()) {
for (auto i : pos->second->ints()) {
if (i == std::numeric_limits<int64_t>::max()) {
ends_vals.add_ints(-1);
} else {
ends_vals.add_ints(i < 0 ? i - 1 : i);
}
}
args.erase(pos);
}
caffe2::Argument axes_vals;
axes_vals.set_name("values");
pos = args.find("axes");
if (pos != args.end()) {
for (auto i : pos->second->ints()) {
axes_vals.add_ints(i);
}
args.erase(pos);
} else {
auto ndim = starts_vals.ints_size();
for (int64_t i = 0; i < ndim; ++i) {
axes_vals.add_ints(i);
}
}
CAFFE_ENFORCE_GE(op->input_size(), 1);
auto data = op->input(0);
auto shape_tensor = dummy_->NewDummyName();
Caffe2Ops ret;
auto* c2_op = ret.ops.Add();
BuildOperator(c2_op, "Shape", {data}, {shape_tensor});
auto axes_tensor = dummy_->NewDummyName();
c2_op = ret.ops.Add();
{
caffe2::Argument shape;
shape.set_name("shape");
shape.add_ints(axes_vals.ints_size());
BuildOperator(
c2_op, "GivenTensorIntFill", {}, {axes_tensor}, {shape, axes_vals});
}
auto starts_vals_tensor = dummy_->NewDummyName();
auto starts_tensor = dummy_->NewDummyName();
c2_op = ret.ops.Add();
{
caffe2::Argument shape_starts;
shape_starts.set_name("shape");
shape_starts.add_ints(starts_vals.ints_size());
BuildOperator(