forked from pytorch/glow
/
ONNXModelLoader.cpp
2457 lines (2103 loc) · 87.3 KB
/
ONNXModelLoader.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "glow/Importer/ONNXModelLoader.h"
#include "glow/Base/Tensor.h"
#include "glow/Graph/Graph.h"
#include "glow/Graph/Nodes.h"
#include "glow/Support/ZipUtils.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace glow;
using llvm::cast;
namespace {
llvm::cl::OptionCategory onnxModelLoaderCat("ONNX Model Loader Options");
std::vector<std::string> onnxDefineSymbol;
llvm::cl::list<std::string, std::vector<std::string>> onnxDefineSymbolOpt(
"onnx-define-symbol", llvm::cl::ZeroOrMore,
llvm::cl::location(onnxDefineSymbol),
llvm::cl::desc(
"Define (replace) the undefined symbols from the tensor descriptions\n"
"in the ONNX model with actual integer sizes. The undefined symbols \n"
"are marked in the proto description with the 'dim_param' field. For\n"
"example, if the model contains a tensor with the size described as \n"
"'None' x 3 x 224 x 224, the symbol 'None' can be replaced with an \n"
"actual integer size (for example 1) by using the following command \n"
"line option: \n"
" -onnx-define-symbol=None,1 \n"
"Multiple symbols can be defined using this option, for example: \n"
" -onnx-define-symbol=<symbol_name1>,<symbol_value1> \n"
" -onnx-define-symbol=<symbol_name2>,<symbol_value2> \n"
" ..................................................\n"),
llvm::cl::value_desc("name,value"), llvm::cl::cat(onnxModelLoaderCat));
/// Parse the command line option and get the user defined map of symbols.
/// The command line option has the format <symbol_name>,<symbol_value>.
Expected<std::unordered_map<std::string, dim_t>> getSymbolMap() {
std::unordered_map<std::string, dim_t> symbolMap;
for (const auto &str : onnxDefineSymbol) {
auto strPair = llvm::StringRef(str).split(',');
llvm::StringRef name = strPair.first;
RETURN_ERR_IF_NOT(name.size() > 0, "ONNX defined symbol name is empty.");
dim_t value;
RETURN_ERR_IF_NOT(!strPair.second.getAsInteger(0, value),
strFormat("ONNX defined symbol value '%s' is invalid.",
strPair.second.data()));
symbolMap[name.str()] = value;
}
return symbolMap;
}
/// Get the shape of a TensorShapeProto given by \p shapeProto and return the
/// dimensions in the vector \p dim passed by reference.
Expected<std::vector<dim_t>>
getProtoShape(const ONNX_NAMESPACE::TensorShapeProto &shapeProto) {
std::vector<dim_t> dim;
for (auto d : shapeProto.dim()) {
if (d.has_dim_value()) {
// Proto shape has an explicit size given by the "dim_value" field.
dim.push_back(d.dim_value());
} else if (d.has_dim_param()) {
// Proto shape has a symbolic size given by the "dim_param" field. Search
// the symbol in the user defined map of symbols. If the symbol is not
// found then raise an error.
auto symbolName = d.dim_param();
std::unordered_map<std::string, dim_t> symbolMap;
ASSIGN_VALUE_OR_RETURN_ERR(symbolMap, getSymbolMap());
if (symbolMap.count(symbolName)) {
dim.push_back(symbolMap[symbolName]);
} else {
RETURN_ERR(strFormat(
"ONNX model symbol '%s' is undefined. Define the symbol with the "
"following command line option: -onnx-define-symbol=%s,<value>.",
symbolName.c_str(), symbolName.c_str()));
}
} else {
// Proto shape has no "dim_value" and no "dim_param" field.
RETURN_ERR("Tensor shape proto has no 'dim_value' or 'dim_param' field!");
}
}
return dim;
}
/// Creates tensor \p T from the input \p in. Note, there is no data associated
/// with the Tensor. This method makes sure that the tensor is created with the
/// proper shape and element type.
Error setTensorType(const ONNX_NAMESPACE::TypeProto &in, Tensor *T) {
std::vector<dim_t> dim;
ASSIGN_VALUE_OR_RETURN_ERR(dim, getProtoShape(in.tensor_type().shape()));
if (in.tensor_type().elem_type() == ONNX_NAMESPACE::TensorProto::FLOAT) {
T->reset(ElemKind::FloatTy, dim);
return Error::success();
} else if (in.tensor_type().elem_type() ==
ONNX_NAMESPACE::TensorProto::INT64) {
T->reset(ElemKind::Int64ITy, dim);
return Error::success();
} else if (in.tensor_type().elem_type() ==
ONNX_NAMESPACE::TensorProto::INT32) {
T->reset(ElemKind::Int32ITy, dim);
return Error::success();
} else {
RETURN_ERR("Only float and index tensors are supported");
}
}
} // namespace
using ArgumentDictionaryTy =
std::unordered_map<std::string, const ONNX_NAMESPACE::AttributeProto *>;
/// Translates the protocol buffer node \p op into a random access map.
static ArgumentDictionaryTy
loadArgumentMap(const ONNX_NAMESPACE::NodeProto &op) {
ArgumentDictionaryTy dict;
for (auto &arg : op.attribute()) {
dict[arg.name()] = &arg;
}
return dict;
}
void glow::setOnnxDefineSymbol(const std::vector<std::string> &strs) {
onnxDefineSymbol = strs;
}
/// Loads tensor \p T from the input \p in.
Error glow::loadTensor(const ONNX_NAMESPACE::TensorProto &in, Tensor *T) {
std::vector<dim_t> dim;
for (auto d : in.dims()) {
dim.push_back(d);
}
if (in.data_type() == ONNX_NAMESPACE::TensorProto::FLOAT) {
T->reset(ElemKind::FloatTy, dim);
if (in.float_data_size() > 0) {
auto TH = T->getHandle<>();
size_t i = 0;
for (auto f : in.float_data()) {
TH.raw(i++) = f;
}
} else if (in.has_raw_data()) {
std::istringstream inStream(in.raw_data(), std::stringstream::binary);
inStream.read(T->getUnsafePtr(), T->size() * sizeof(float));
} else {
RETURN_ERR("Unsupported Tensor format.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
}
} else if (in.data_type() == ONNX_NAMESPACE::TensorProto::INT64) {
T->reset(ElemKind::Int64ITy, dim);
if (in.int64_data_size() > 0) {
auto TH = T->getHandle<int64_t>();
size_t i = 0;
for (auto f : in.int64_data()) {
TH.raw(i++) = f;
}
} else if (in.has_raw_data()) {
std::istringstream inStream(in.raw_data(), std::stringstream::binary);
inStream.read(T->getUnsafePtr(), T->size() * sizeof(int64_t));
} else {
RETURN_ERR("Unsupported Tensor format.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
}
} else if (in.data_type() == ONNX_NAMESPACE::TensorProto::INT32) {
// There are few cases when we will have int32 tensors. For example, the
// second output of Concat from Caffe2 concat op is int32
T->reset(ElemKind::Int32ITy, dim);
if (in.int32_data_size() > 0) {
auto TH = T->getHandle<int32_t>();
size_t i = 0;
for (auto f : in.int32_data()) {
TH.raw(i++) = f;
}
} else if (in.has_raw_data()) {
std::istringstream inStream(in.raw_data(), std::stringstream::binary);
inStream.read(T->getUnsafePtr(), T->size() * sizeof(int32_t));
} else {
RETURN_ERR("Unsupported Tensor format.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
}
} else if (in.data_type() == ONNX_NAMESPACE::TensorProto::UINT8) {
const auto &elementType = in.doc_string();
if (elementType == Type::getElementName(ElemKind::UInt8FusedQTy)) {
T->reset(ElemKind::UInt8FusedQTy, dim, 0.0, 0);
} else {
RETURN_ERR("Unsupported Tensor element type " + elementType,
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
}
if (in.has_raw_data()) {
std::istringstream inStream(in.raw_data(), std::stringstream::binary);
inStream.read(T->getUnsafePtr(), T->size() * sizeof(uint8_t));
} else {
RETURN_ERR("Unsupported Tensor format.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
}
} else if (in.data_type() == ONNX_NAMESPACE::TensorProto::BOOL) {
T->reset(ElemKind::BoolTy, dim);
if (in.has_raw_data()) {
std::istringstream inStream(in.raw_data(), std::stringstream::binary);
inStream.read(T->getUnsafePtr(), T->size() * sizeof(bool));
} else {
RETURN_ERR("Unsupported Tensor format.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
}
} else {
RETURN_ERR("Only float and index tensors are supported",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
}
return Error::success();
}
Error ONNXModelLoader::loadInputs(ONNX_NAMESPACE::GraphProto &net,
bool loadInputsAsPlaceholders) {
for (const auto &in : net.input()) {
// Skip static weights.
if (getConstantByNameOrNull(in.name())) {
continue;
}
if (loadInputsAsPlaceholders) {
Tensor T;
RETURN_IF_ERR(setTensorType(in.type(), &T));
Placeholder *placeholder;
ASSIGN_VALUE_OR_RETURN_ERR(
placeholder, createAndRegisterPlaceholder(in.name(), &T.getType()));
inputVarsByName_.try_emplace(in.name(), placeholder);
} else {
Tensor T;
RETURN_IF_ERR(setTensorType(in.type(), &T));
RETURN_IF_ERR(createAndRegisterConstant(in.name(), std::move(T)));
}
}
return Error::success();
}
Expected<bool> ONNXModelLoader::getBroadcast(const ArgumentDictionaryTy &dict) {
// Starting with opset 7, broadcasting is implicit and doesn't require any
// attribute.
if (opsetVersion_ > 6) {
return true;
}
if (!dict.count("broadcast")) {
return false;
}
int broadcast;
ASSIGN_VALUE_OR_RETURN_ERR(broadcast, loadInt(dict.at("broadcast")));
return broadcast == 1;
}
bool ONNXModelLoader::hasMultidirectionalBroadcast(
const llvm::StringRef typeName) {
// Before opset 7, broadcasting was unidirectional.
if (opsetVersion_ > 6) {
if ((typeName == "Add") || (typeName == "Sub") || (typeName == "Mul") ||
(typeName == "Div")) {
return true;
}
// TODO: some other operators also support multidirectional broadcasting.
}
return false;
}
Expected<ElemKind> ONNXModelLoader::convertTensorProtoDataType(
ONNX_NAMESPACE::TensorProto_DataType t) {
switch (t) {
case ONNX_NAMESPACE::TensorProto_DataType_FLOAT:
return ElemKind::FloatTy;
case ONNX_NAMESPACE::TensorProto_DataType_FLOAT16:
return ElemKind::Float16Ty;
case ONNX_NAMESPACE::TensorProto_DataType_INT32:
return ElemKind::Int32ITy;
case ONNX_NAMESPACE::TensorProto_DataType_INT64:
return ElemKind::Int64ITy;
default:;
}
RETURN_ERR("Non supported ONNX type");
}
Error ONNXModelLoader::setVersion(ONNX_NAMESPACE::ModelProto MP) {
irVersion_ = MP.ir_version();
opsetVersion_ = 0;
RETURN_ERR_IF_NOT(
irVersion_ >= 3,
"This ONNX model with ir_version < 3 is too old to be supported.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_ONNX_VERSION);
for (const auto &imp : MP.opset_import()) {
if (!imp.has_domain() || imp.domain() == "") {
opsetVersion_ = imp.version();
break;
}
}
RETURN_ERR_IF_NOT(opsetVersion_ > 0,
"The opset of this ONNX model is not supported.");
return Error::success();
}
Expected<ONNX_NAMESPACE::ModelProto>
ONNXModelLoader::loadProto(google::protobuf::io::ZeroCopyInputStream &iStream) {
// Construct and configure a Coded Input Stream
google::protobuf::io::CodedInputStream codedStream(&iStream);
// Don't warn about large file sizes.
codedStream.SetTotalBytesLimit(MAX_PROTO_SIZE, MAX_PROTO_SIZE);
ONNX_NAMESPACE::ModelProto MP;
bool parseNet = MP.ParseFromCodedStream(&codedStream);
RETURN_ERR_IF_NOT(parseNet, "Failed to parse ModelProto",
ErrorValue::ErrorCode::MODEL_LOADER_INVALID_PROTOBUF);
return MP;
}
Expected<ONNX_NAMESPACE::ModelProto>
ONNXModelLoader::loadProto(const void *onnxModel, size_t onnxModelSize) {
google::protobuf::io::ArrayInputStream arrayStream(onnxModel, onnxModelSize);
return loadProto(arrayStream);
}
Expected<ONNX_NAMESPACE::ModelProto>
ONNXModelLoader::loadProto(const std::string &filename) {
std::ifstream ff(filename, std::ios::in | std::ios::binary);
RETURN_ERR_IF_NOT(ff,
strFormat("Can't find the model or network files for %s.",
filename.c_str()),
ErrorValue::ErrorCode::MODEL_LOADER_INVALID_PROTOBUF);
// TODO: intend to find a way to reuse the following function later
// for the text format onnx model:
// bool ONNXModelLoader::loadProto(ONNX_NAMESPACE::GraphProto &net,
// google::protobuf::io::ZeroCopyInputStream &iStream)
if (filename.find(".onnxtxt") != std::string::npos) {
std::string str((std::istreambuf_iterator<char>(ff)),
std::istreambuf_iterator<char>());
ONNX_NAMESPACE::ModelProto MP;
bool parseNet = google::protobuf::TextFormat::ParseFromString(str, &MP);
RETURN_ERR_IF_NOT(parseNet, "Failed to parse ModelProto",
ErrorValue::ErrorCode::MODEL_LOADER_INVALID_PROTOBUF);
return MP;
}
google::protobuf::io::IstreamInputStream fileStream(&ff);
return loadProto(fileStream);
}
namespace {
/// Helper type for pads.
using Pads = std::vector<unsigned_t>;
} // namespace
/// Get the Pads value based on setting for auto_pad.
/// \p kdim : kernel sizes (HW)
/// \p sdim: stride sizes (HW)
/// \p idim: input sizes (HW)
Expected<Pads> getPads(const ArgumentDictionaryTy &dict,
llvm::ArrayRef<unsigned_t> kdim,
llvm::ArrayRef<unsigned_t> sdim,
llvm::ArrayRef<unsigned_t> idim) {
if (dict.count("pads")) {
return getShape<unsigned_t>(dict.at("pads"));
}
if (dict.count("auto_pad")) {
std::string padStr;
ASSIGN_VALUE_OR_RETURN_ERR(padStr, loadStr(dict.at("auto_pad")));
if (padStr == "VALID") {
// Return default value 0 for pads.
return Pads({0, 0, 0, 0});
} else if (padStr == "SAME_UPPER" || padStr == "SAME_LOWER") {
unsigned_t top, left, bottom, right;
// From https://arxiv.org/pdf/1603.07285.pdf 2.4,
// o = floor((i + 2*p - k)/s) + 1
// Also, from https://github.com/onnx/onnx/blob/master/docs/Operators.md
// output_spatial_shape[i] =
// ceil(input_spatial_shape[i] / strides_spatial_shape[i])
// pad_shape[i] =
// (output_spatial_shape[i] - 1) * strides_spatial_shape[i]
// + kernel_spatial_shape[i] - input_spatial_shape[i]
// Use the smallest padding possible out of the possible options.
llvm::SmallVector<unsigned_t, 2> pdim(2); // Total Paddding, HW.
for (size_t i = 0, e = pdim.size(); i < e; i++) {
pdim[i] = sdim[i] * (idim[i] - 1) + kdim[i] - idim[i];
}
if (padStr == "SAME_UPPER") {
// SAME_UPPPER: if odd number for pdim[i], use extra padding at the end.
top = pdim[0] / 2;
bottom = top + (pdim[0] & 0x1);
left = pdim[1] / 2;
right = left + (pdim[1] & 0x1);
} else {
// SAME_LOWER: if odd number for pdim[i], use extra padding at the
// beginning.
bottom = pdim[0] / 2;
top = bottom + (pdim[0] & 0x1);
right = pdim[1] / 2;
left = right + (pdim[1] & 0x1);
}
return Pads({top, left, bottom, right});
}
RETURN_ERR("only auto_pad==VALID, SAME_UPPER and SAME_LOWER are supported");
}
// Return default value 0 for pads.
return Pads({0, 0, 0, 0});
}
Error ONNXModelLoader::loadConstant(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
/*
output: "Parameter6"
name: "Parameter6"
op_type: "Constant"
attribute {
name: "value"
t {
dims: 8
data_type: FLOAT
float_data: -0.161539719
float_data: -0.433835655
float_data: 0.091641359
float_data: -0.0168522168
float_data: -0.0650264397
float_data: -0.131737873
float_data: 0.0204175506
float_data: -0.121110231
}
type: TENSOR
}
doc_string: ""
domain: ""
*/
const auto &name = op.output(0);
// If the tensor is pre-populated by the user of this class then we don't
// need to allocate a new tensor.
if (getConstantByNameOrNull(name)) {
return Error::success();
}
RETURN_ERR_IF_NOT(dict.at("value")->type() ==
ONNX_NAMESPACE::AttributeProto::TENSOR,
"Only Tensor type constants are supported.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_DATATYPE);
Tensor T;
RETURN_IF_ERR(loadTensor(dict.at("value")->t(), &T));
RETURN_IF_ERR(createAndRegisterConstant(name, std::move(T)));
return Error::success();
}
/// Retrieves data from a constant Tensor and stores it in a vector.
template <typename T>
static void helperSetter(Constant *constT, std::vector<ssize_t> &vec) {
auto constH = constT->getPayload().getHandle<T>();
for (dim_t i = 0; i < constH.size(); ++i) {
vec.push_back(constH.at({i}));
}
}
Error ONNXModelLoader::loadSlice(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
NodeValue data;
ASSIGN_VALUE_OR_RETURN_ERR(data, getNodeValueByName(op.input(0)));
auto dims = data.dims();
auto numDims = dims.size();
std::vector<ssize_t> starts;
std::vector<ssize_t> ends;
// Attribute 'axes' is optional.
std::vector<ssize_t> axes;
if (this->opsetVersion_ >= 10) {
Constant *startsC = getConstantByNameOrNull(op.input(1));
Constant *endsC = getConstantByNameOrNull(op.input(2));
RETURN_ERR_IF_NOT(startsC, "Starts Tensor is not Constant.");
RETURN_ERR_IF_NOT(endsC, "Ends Tensor is not Constant.");
if (startsC->getElementType() == ElemKind::Int64ITy) {
helperSetter<int64_t>(startsC, starts);
} else if (startsC->getElementType() == ElemKind::Int32ITy) {
helperSetter<int32_t>(startsC, starts);
} else {
RETURN_ERR_IF_NOT(false, "Starts Tensor has unsupported type.");
}
if (endsC->getElementType() == ElemKind::Int64ITy) {
helperSetter<int64_t>(endsC, ends);
} else if (endsC->getElementType() == ElemKind::Int32ITy) {
helperSetter<int32_t>(endsC, ends);
} else {
RETURN_ERR_IF_NOT(false, "Ends Tensor has unsupported type.");
}
if (op.input_size() > 3) {
Constant *axesC = getConstantByNameOrNull(op.input(3));
RETURN_ERR_IF_NOT(startsC, "Axes Tensor is not Constant.");
if (axesC->getElementType() == ElemKind::Int64ITy) {
helperSetter<int64_t>(axesC, axes);
} else if (axesC->getElementType() == ElemKind::Int32ITy) {
helperSetter<int32_t>(axesC, axes);
} else {
RETURN_ERR_IF_NOT(false, "Axes Tensor has unsupported type.");
}
RETURN_ERR_IF_NOT(op.input_size() == 5,
"Steps is not currently supported.");
}
} else {
// Attributes 'starts' and 'ends' are mandatory and must be consistent.
RETURN_ERR_IF_NOT(dict.count("starts"),
"Slice: attribute 'starts' is mandatory.");
RETURN_ERR_IF_NOT(dict.count("ends"),
"Slice: attribute 'ends' is mandatory.");
starts = getShape<ssize_t>(dict.at("starts"));
ends = getShape<ssize_t>(dict.at("ends"));
if (dict.count("axes")) {
// The ONNX spec is unclear so we consider that the 'axes' array may have
// any size. The constraints are:
// - the element value must be in range [0, numDims),
// - 'starts' & 'ends' arrays must have the same size as the 'axes' array.
// In case an axis is specified multiple times in 'axes', the later
// parameters will simply overwrite the previous ones.
axes = getShape<ssize_t>(dict.at("axes"));
}
}
RETURN_ERR_IF_NOT(
(starts.size() == ends.size()),
"Slice: 'starts' and 'ends' arrays must have the same size.");
if (axes.empty()) {
for (size_t i = 0; i < numDims; i++) {
axes.push_back(ssize_t(i));
}
}
// The ONNX description is unclear and doesn't describe what to do when a
// an axis index is not given in the axes array. An interpretation is that
// for such an axis, the entire range is taken. Then, we initialize
// newStarts and newEnds with the full range for all axes.
std::vector<dim_t> newStarts(numDims);
std::vector<dim_t> newEnds(numDims);
for (size_t i = 0; i < numDims; i++) {
newStarts[i] = 0;
newEnds[i] = dims[i];
}
// Determine the coordinates of the sub-tensor to extract.
RETURN_ERR_IF_NOT(axes.size() == starts.size(),
"'axes' and 'starts' must be the same size.");
RETURN_ERR_IF_NOT(starts.size() == ends.size(),
"'starts' and 'ends' must be the same size.");
for (size_t i = 0; i < axes.size(); i++) {
ssize_t newStart = starts[i];
ssize_t newEnd = ends[i];
ssize_t axisId = axes[i];
RETURN_ERR_IF_NOT((axisId >= 0) && (axisId < ssize_t(numDims)),
"Axes indexes must be within the input tensor range.");
// ONNX: "If the value passed to start or end is larger than the n (the
// number of elements in this dimension), it represents n".
if (newStart > ssize_t(dims[axisId])) {
newStart = ssize_t(dims[axisId]);
}
if (newEnd > ssize_t(dims[axisId])) {
newEnd = ssize_t(dims[axisId]);
}
// The ONNX description is unclear and the numpy definition is more
// accurate.
// - ONNX: "Similar to numpy. [...]. If a negative value is passed for any
// of the start or end indices, it represent number of elements before the
// end of that dimension."
// - Numpy: "Negative indices are interpreted as counting from the end of
// the array (i.e., if n_i < 0, it means n_i + d_i)."
if (newStart < 0) {
newStart = ssize_t(dims[axisId]) + newStart;
RETURN_ERR_IF_NOT(newStart >= 0,
"Slice: final start index should never be negative.");
}
if (newEnd < 0) {
newEnd = ssize_t(dims[axisId]) + newEnd;
RETURN_ERR_IF_NOT(newEnd >= 0,
"Slice: final end index should never be negative.");
}
newStarts[axisId] = size_t(newStart);
newEnds[axisId] = size_t(newEnd);
}
// Create the IR node.
Node *SN = G_.createSlice(opName, data, newStarts, newEnds);
RETURN_IF_ERR(addNodeAsOutput(op, SN));
return Error::success();
}
Error ONNXModelLoader::loadConv(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
// Load the attributes
std::vector<unsigned_t> strides(2, 1);
if (dict.count("strides")) {
strides = getShape<unsigned_t>(dict.at("strides"));
}
unsigned_t group = 1;
if (dict.count("group")) {
ASSIGN_VALUE_OR_RETURN_ERR(group, loadInt(dict.at("group")));
}
unsigned_t dilation = 1;
if (dict.count("dilations")) {
std::vector<unsigned_t> dilations(2, 1);
dilations = getShape<unsigned_t>(dict.at("dilations"));
RETURN_ERR_IF_NOT(dilations.size() == 2,
"Conv: dilations must be specified for 2 axes.");
RETURN_ERR_IF_NOT(dilations[1] == dilations[0],
"Conv: different dilation values along different axes "
"are not supported currently. values must be same.");
dilation = dilations[0];
}
// Load the inputs
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
NodeValue filterValue;
ASSIGN_VALUE_OR_RETURN_ERR(filterValue, getNodeValueByName(op.input(1)));
// Transpose the filter to the right format. Glow expects to read the
// weights in the format CRSK. ONNX stores the operators as KCRS.
// C - output_depth, R - filter_height, S - filter_width, K - input_depth.
TransposeNode *filterTransposeNode =
G_.createTranspose(opName, filterValue, NCHW2NHWC);
// The structure of the conv weights is: CRSK. We take the C, which is the
// number of filters. We use this value to calculate the size of the bias
// if it is not specified.
const NodeValue filterTransposedValue = filterTransposeNode->getResult();
dim_t depth = filterTransposedValue.dims()[0];
// Get the kernel shape from the input.
llvm::SmallVector<unsigned_t, 2> kernelShape(2);
kernelShape[0] = filterTransposedValue.dims()[1];
kernelShape[1] = filterTransposedValue.dims()[2];
// Extra check when the 'kernel_shape' attribute exists.
// The 'kernel_shape' attribute is redundant not mandatory.
if (dict.count("kernel_shape")) {
auto kernelShapeAttribute = getShape<unsigned_t>(dict.at("kernel_shape"));
RETURN_ERR_IF_NOT(
(kernelShape[0] == kernelShapeAttribute[0] &&
kernelShape[1] == kernelShapeAttribute[1]),
"The 'kernel_shape' attribute is not consistent with the actual "
"convolution kernel shape.");
(void)kernelShapeAttribute; // Avoids compilation warning in release mode.
}
// Construct the Bias field.
Constant *bias = nullptr;
// Check if we have a serialized bias vector.
if (op.input_size() > 2) {
auto &biasTensorName = op.input(2);
// Load the serialized bias vector.
ASSIGN_VALUE_OR_RETURN_ERR(bias, getConstantByName(biasTensorName));
}
// If a serialized bias wasn't found then create a zero bias.
if (!bias) {
Tensor biasTensor(ElemKind::FloatTy, {depth});
biasTensor.zero();
bias = G_.getParent()->createConstant("conv.bias", std::move(biasTensor));
}
// ONNX passes the input as NCHW, and we expect the input to be NHWC.
auto *tr = G_.createTranspose(opName, in, NCHW2NHWC);
// Calculate the size and allocate the output buffer.
ShapeNHWC idim = ShapeNHWC(tr->getResult().dims());
llvm::SmallVector<unsigned_t, 2> idimHW(2);
idimHW[0] = in.dims()[2];
idimHW[1] = in.dims()[3];
// Pads : {pad_top, pad_left, pad_bottom, pad_right}
Pads pads;
ASSIGN_VALUE_OR_RETURN_ERR(pads, getPads(dict, kernelShape, strides, idimHW));
auto outSz = calculateConvPoolOutputDims(idim.h, idim.w, kernelShape, strides,
pads, dilation);
std::array<dim_t, 4> outDims = {{idim.n, outSz.first, outSz.second, depth}};
auto outTy = G_.getParent()->uniqueType(ElemKind::FloatTy, outDims);
auto *node = G_.createConv(opName, tr, filterTransposeNode, bias, outTy,
kernelShape, strides, pads, group, dilation);
// Transpose the output back.
auto *N = G_.createTranspose(opName, node, NHWC2NCHW);
RETURN_IF_ERR(addNodeAsOutput(op, N));
return Error::success();
}
Error ONNXModelLoader::loadPool(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict,
llvm::StringRef typeName) {
const std::string &opName = loadOperatorName(op);
// Load the inputs:
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
std::vector<unsigned_t> strides(2, 1);
if (dict.count("strides")) {
strides = getShape<unsigned_t>(dict.at("strides"));
}
auto kernels = getShape<unsigned_t>(dict.at("kernel_shape"));
if (in.dims().size() != 4 || kernels.size() != 2) {
// Glow only handles 2D pooling currently.
RETURN_ERR("Glow only handles 2D pooling currently.",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_SHAPE);
}
auto *tr = G_.createTranspose(opName, in, NCHW2NHWC);
// If 'global_pooling' is set then the operation will pool over the size of
// the input by doing: kernel = height/width.
if (dict.count("global_pooling")) {
auto Ty = in.getType();
kernels[0] = Ty->dims()[2];
kernels[1] = Ty->dims()[3];
}
// NHWC
llvm::SmallVector<unsigned_t, 2> idimHW(2);
idimHW[0] = in.dims()[1];
idimHW[1] = in.dims()[2];
Pads pads;
ASSIGN_VALUE_OR_RETURN_ERR(pads, getPads(dict, kernels, strides, idimHW));
Node *node = nullptr;
if (op.output_size() > 1) {
if (typeName != "MaxPool") {
RETURN_ERR("Argmax output is only supported for MaxPool!",
ErrorValue::ErrorCode::MODEL_LOADER_UNSUPPORTED_OPERATOR);
}
node = G_.createMaxPool(opName, tr, kernels, strides, pads);
auto *res = G_.createTranspose(opName, NodeValue(node, 0), NHWC2NCHW);
auto *argmax = G_.createTranspose(opName, NodeValue(node, 1), NHWC2NCHW);
RETURN_IF_ERR(assignNodeOutputs(op, {res, argmax}));
} else {
size_t idx = 0;
if (typeName == "MaxPool") {
node = G_.createMaxPool(opName, tr, kernels, strides, pads);
idx = MaxPoolNode::ResultIdx;
} else {
node = G_.createAvgPool(opName, tr, kernels, strides, pads);
idx = AvgPoolNode::ResultIdx;
}
auto *N = G_.createTranspose(opName, NodeValue(node, idx), NHWC2NCHW);
RETURN_IF_ERR(addNodeAsOutput(op, N));
}
return Error::success();
}
Error ONNXModelLoader::loadArgMax(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
size_t axis = 0;
if (dict.count("axis")) {
ASSIGN_VALUE_OR_RETURN_ERR(axis, loadInt(dict.at("axis")));
}
bool keepDims = true;
if (dict.count("keepDims")) {
ASSIGN_VALUE_OR_RETURN_ERR(keepDims, loadInt(dict.at("keepDims")));
}
Node *node = G_.createArgMax(opName, in, axis, keepDims);
RETURN_IF_ERR(addNodeAsOutput(op, node));
return Error::success();
}
Error ONNXModelLoader::loadGlobalAveragePool(
const ONNX_NAMESPACE::NodeProto &op, const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
// Load the inputs:
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
std::vector<unsigned_t> strides(2, 1);
if (dict.count("strides")) {
strides = getShape<unsigned_t>(dict.at("strides"));
}
llvm::SmallVector<unsigned_t, 2> kernels(2);
kernels[0] = in.dims()[2];
kernels[1] = in.dims()[3];
Pads pads;
ASSIGN_VALUE_OR_RETURN_ERR(
pads, getPads(dict, kernels, strides, kernels /* input sizes*/));
auto *tr = G_.createTranspose(opName, in, NCHW2NHWC);
Node *node = G_.createAvgPool(opName, tr, kernels, strides, pads);
auto *N = G_.createTranspose(opName, node, NHWC2NCHW);
RETURN_IF_ERR(addNodeAsOutput(op, N));
return Error::success();
}
Error ONNXModelLoader::loadSqueeze(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
auto axes = getShape(dict.at("axes"));
Node *node = G_.createSqueeze(opName, in, axes);
RETURN_IF_ERR(addNodeAsOutput(op, node));
return Error::success();
}
Error ONNXModelLoader::loadUnsqueeze(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
auto axes = getShape(dict.at("axes"));
Node *node = G_.createExpandDims(opName, in, axes);
RETURN_IF_ERR(addNodeAsOutput(op, node));
return Error::success();
}
Error ONNXModelLoader::loadBatchNormalization(
const ONNX_NAMESPACE::NodeProto &op, const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
Constant *scale;
ASSIGN_VALUE_OR_RETURN_ERR(scale, getConstantByName(op.input(1)));
Constant *bias;
ASSIGN_VALUE_OR_RETURN_ERR(bias, getConstantByName(op.input(2)));
Constant *mean;
ASSIGN_VALUE_OR_RETURN_ERR(mean, getConstantByName(op.input(3)));
Constant *var;
ASSIGN_VALUE_OR_RETURN_ERR(var, getConstantByName(op.input(4)));
float epsilon = 1e-5f; // default
auto epsilonIt = dict.find("epsilon");
if (epsilonIt != dict.end()) {
ASSIGN_VALUE_OR_RETURN_ERR(epsilon, loadFloat(epsilonIt->second));
}
auto *node = G_.createBatchNormalization(opName, in, bias, scale, mean, var,
1, epsilon);
// BatchNormalization has 4 optional outputs that are not supported by glow.
// Then: 1/ In case the optional outputs are present and used by other
// operations of the model, then the import should fail. 2/ In case the
// optional outputs are declared but not used, the import should succeed. By
// registering only the mandatory output, we make sure the import will fail if
// the non supported features are actually requested by the ONNX model.
RETURN_IF_ERR(addNodeAsOutput(op, node, 1));
return Error::success();
}
Error ONNXModelLoader::loadConcat(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
const unsigned numInputs = op.input_size();
llvm::SmallVector<NodeValue, 4> inputs;
inputs.reserve(numInputs);
for (unsigned i = 0; i < numInputs; i++) {
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(i)));
inputs.push_back(in);
}
int axis;
ASSIGN_VALUE_OR_RETURN_ERR(axis, loadInt(dict.at("axis")));
Node *node = G_.createConcat(opName, inputs, axis);
RETURN_IF_ERR(addNodeAsOutput(op, node));
return Error::success();
}
Error ONNXModelLoader::loadFCTransposed(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
NodeValue in;
ASSIGN_VALUE_OR_RETURN_ERR(in, getNodeValueByName(op.input(0)));
if (in.getType()->dims().size() > 2) {
size_t axis = 1;
if (dict.count("axis")) {
ASSIGN_VALUE_OR_RETURN_ERR(axis, loadInt(dict.at("axis")));
}
in = G_.createFlatten("fc.in", in, axis);
}
unsigned_t axis_w = 1;
if (dict.count("axis_w")) {
ASSIGN_VALUE_OR_RETURN_ERR(axis_w, loadInt(dict.at("axis_w")));
}
Constant *W;
ASSIGN_VALUE_OR_RETURN_ERR(W, getConstantByName(op.input(1)));
// w is stored already transposed. No need to additionally transpose it.
if (W->dims().size() > 2) {
Tensor tmp;
auto wDims = flattenCdr(W->dims(), axis_w);
tmp.reset(ElemKind::FloatTy, {wDims.first, wDims.second});
tmp.copyRawFrom(&W->getPayload());
W = G_.getParent()->createConstant(W->getName(), tmp);
}
Constant *B;
ASSIGN_VALUE_OR_RETURN_ERR(B, getConstantByName(op.input(2)));
auto *node = G_.createFullyConnected(opName, in, W, B);
RETURN_IF_ERR(addNodeAsOutput(op, node));
return Error::success();
}
Error ONNXModelLoader::loadGemm(const ONNX_NAMESPACE::NodeProto &op,
const ArgumentDictionaryTy &dict) {
const std::string &opName = loadOperatorName(op);
NodeValue A;
ASSIGN_VALUE_OR_RETURN_ERR(A, getNodeValueByName(op.input(0)));
NodeValue B;
ASSIGN_VALUE_OR_RETURN_ERR(B, getNodeValueByName(op.input(1)));
NodeValue C;
ASSIGN_VALUE_OR_RETURN_ERR(C, getNodeValueByName(op.input(2)));
bool broadcastC;
ASSIGN_VALUE_OR_RETURN_ERR(broadcastC, getBroadcast(dict));
bool transA = false;
if (dict.count("transA")) {
ASSIGN_VALUE_OR_RETURN_ERR(transA, loadInt(dict.at("transA")));
}
bool transB = false;
if (dict.count("transB")) {
ASSIGN_VALUE_OR_RETURN_ERR(transB, loadInt(dict.at("transB")));
}
// TODO: support alpha * A * B + beta * C
if (transA)
A = G_.createTranspose(opName, A, {1, 0});
if (transB)
B = G_.createTranspose(opName, B, {1, 0});
MatMulNode *mul = G_.createMatMul(opName, A, B);
if (broadcastC) {
int axis = mul->getResult().dims().size() - C.dims().size();
C = G_.createBroadcast(opName, C, mul->getResult().dims(), axis);
}
Node *node = G_.createAdd(opName, mul, C);