-
Notifications
You must be signed in to change notification settings - Fork 319
/
gen_onnx_mlir.py
executable file
·1603 lines (1430 loc) · 49.9 KB
/
gen_onnx_mlir.py
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
#!/usr/bin/env python3
# After modifying this file, the script will need to run to rebuild the
# onnx-mlir ONNX Dialect. This is performed by calling
# `make OMONNXOpsIncTranslation` in the build dir.
# If the changes are not seen, then you need to rebuild the entire onnx-mlir.
# After changes that impact the documentation of the ops, run
# "make onnx-mlir-docs".
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import defaultdict, OrderedDict
from io import StringIO
import io
import os
import sys
import datetime
import argparse
import numpy as np # type: ignore
from onnx import defs, FunctionProto, helper, OperatorStatus
from onnx.defs import OpSchema, ONNX_DOMAIN, ONNX_ML_DOMAIN
from onnx.backend.test.case import collect_snippets
from onnx.backend.sample.ops import collect_sample_implementations
from typing import Any, Text, Sequence, Dict, List, Type, Set, Tuple
import pprint
import onnx
parser = argparse.ArgumentParser()
parser.add_argument(
"--dry-run-onnx-ops",
help="Output ONNXOps.td.inc content to stdout.",
action="store_true",
default=False,
)
parser.add_argument(
"--dry-run-op-build-table",
help="Output OpBuildTable.inc content to stdout.",
action="store_true",
default=False,
)
parser.add_argument(
"--check-operation-version",
help="check whether the imported onnx package has new operation or "
" newer version of operation compared with version stored in version_dict",
action="store_true",
default=False,
)
parser.add_argument(
"--list-operation-version",
help="list the version stored in version_dict without performing checks",
action="store_true",
default=False,
)
args = parser.parse_args()
check_operation_version = args.check_operation_version
list_operation_version = args.list_operation_version
# ==UPDATE_ONNX_VERSION_OPSET==
# Look for tag above and update all references when upgrading the ONNX support within ONNX-MLIR.
current_onnx_version = "1.17.0"
# Check the version of onnx package being used.
if (
not check_operation_version and not list_operation_version
) and current_onnx_version != onnx.__version__:
print(
"version of expected onnx is {}, ".format(current_onnx_version)
+ "while onnx package being used is {}".format(onnx.__version__)
)
quit()
# Record the version of each operation that is treated as the current version.
# To check whether the onnx package being used has newer version operation,
# run this script with --check-operation-version flag.
# Update this dictionary when a newer version is implemented
# TODO: how to keep the old version
version_dict = {
"Abs": [13],
"Acos": [7],
"Acosh": [9],
"Adagrad": [1],
"Adam": [1],
"Add": [14],
"And": [7],
"ArgMax": [13],
"ArgMin": [13],
"ArrayFeatureExtractor": [1],
"Asin": [7],
"Asinh": [9],
"Atan": [7],
"Atanh": [9],
"AveragePool": [19],
"BatchNormalization": [15],
"Bernoulli": [15],
"Binarizer": [1],
"BitShift": [11],
"BitwiseAnd": [18],
"BitwiseNot": [18],
"BitwiseOr": [18],
"BitwiseXor": [18],
"BlackmanWindow": [17],
"Cast": [19],
"CastLike": [19],
"CastMap": [1],
"CategoryMapper": [1],
"Ceil": [13],
"Celu": [12],
"CenterCropPad": [18],
"Clip": [13, 12, 11, 6],
"Compress": [11],
"Concat": [13],
"ConcatFromSequence": [11],
"Constant": [19],
"ConstantOfShape": [20],
"Conv": [11],
"ConvInteger": [10],
"ConvTranspose": [11],
"Cos": [7],
"Cosh": [9],
"Col2Im": [18],
"CumSum": [14],
"DeformConv": [19],
"DepthToSpace": [13],
"DequantizeLinear": [19],
"Det": [11],
"DFT": [20, 17],
"DictVectorizer": [1],
"Div": [14],
"Dropout": [13],
"DynamicQuantizeLinear": [11],
"Einsum": [12],
"Elu": [6],
"Equal": [19],
"Erf": [13],
"Exp": [13],
"Expand": [13],
"EyeLike": [9],
"FeatureVectorizer": [1],
"Flatten": [13],
"Floor": [13],
"GRU": [14],
"Gather": [13],
"GatherElements": [13],
"GatherND": [13],
"Gelu": [20],
"Gemm": [13],
"GlobalAveragePool": [1],
"GlobalLpPool": [2],
"GlobalMaxPool": [1],
"Gradient": [1],
"Greater": [13],
"GreaterOrEqual": [16],
"GridSample": [16],
"GroupNormalization": [21, 18],
"HammingWindow": [17],
"HannWindow": [17],
"HardSigmoid": [6],
"Hardmax": [13],
"HardSwish": [14],
"Identity": [19],
"If": [19],
"Imputer": [1],
"InstanceNormalization": [6],
"IsInf": [20],
"IsNaN": [20],
"LayerNormalization": [17],
"LRN": [13],
"LSTM": [14],
"LabelEncoder": [2],
"LeakyRelu": [16],
"Less": [13],
"LessOrEqual": [16],
"LinearClassifier": [1],
"LinearRegressor": [1],
"Log": [13],
"LogSoftmax": [13],
"Loop": [19],
"LpNormalization": [1],
"LpPool": [18],
"MatMul": [13],
"MatMulInteger": [10],
"Max": [13],
"MaxPool": [12],
"MaxRoiPool": [1],
"MaxUnpool": [11],
"Mean": [13],
"MeanVarianceNormalization": [13],
"MelWeightMatrix": [17],
"Min": [13],
"Mish": [18],
"Mod": [13],
"Momentum": [1],
"Mul": [14],
"Multinomial": [7],
"Neg": [13],
"NegativeLogLikelihoodLoss": [13],
"NonMaxSuppression": [11],
"NonZero": [13],
"Normalizer": [1],
"Not": [1],
"OneHot": [11],
"OneHotEncoder": [1],
"Optional": [15],
"OptionalGetElement": [18],
"OptionalHasElement": [18],
"Or": [7],
"PRelu": [16],
"Pad": [19, 18, 13, 11, 2],
"Pow": [15],
"QLinearConv": [10],
"QLinearMatMul": [10],
"QuantizeLinear": [19],
"RNN": [14],
"RandomNormal": [1],
"RandomNormalLike": [1],
"RandomUniform": [1],
"RandomUniformLike": [1],
"Range": [11],
"Reciprocal": [13],
"ReduceL1": [18, 13],
"ReduceL2": [18, 13],
"ReduceLogSum": [18, 13],
"ReduceLogSumExp": [18, 13],
"ReduceMax": [20, 18, 13],
"ReduceMean": [18, 13],
"ReduceMin": [20, 18, 13],
"ReduceProd": [18, 13],
"ReduceSum": [13, 11],
"ReduceSumSquare": [18, 13],
"Relu": [14],
"Reshape": [19],
"Resize": [19, 18, 13, 11, 10],
"ReverseSequence": [10],
"RoiAlign": [16],
"Round": [11],
"SVMClassifier": [1],
"SVMRegressor": [1],
"Scaler": [1],
"Scan": [19],
"Scatter": [11],
"ScatterElements": [18],
"ScatterND": [18],
"Selu": [6],
"SequenceAt": [11],
"SequenceConstruct": [11],
"SequenceEmpty": [11],
"SequenceErase": [11],
"SequenceInsert": [11],
"SequenceLength": [11],
"SequenceMap": [17],
"Shape": [19],
"Shrink": [9],
"Sigmoid": [13],
"Sign": [13],
"Sin": [7],
"Sinh": [9],
"Size": [19],
"Slice": [13],
"Softmax": [13, 11],
"SoftmaxCrossEntropyLoss": [13],
"Softplus": [1],
"Softsign": [1],
"SpaceToDepth": [13],
"Split": [18, 13, 11],
"SplitToSequence": [11],
"Sqrt": [13],
"Squeeze": [13, 11],
"StringNormalizer": [10],
"STFT": [17],
"Sub": [14],
"Sum": [13],
"Tan": [7],
"Tanh": [13],
"TfIdfVectorizer": [9],
"ThresholdedRelu": [10],
"Tile": [13],
"TopK": [11],
"Transpose": [13],
"Trilu": [14],
"TreeEnsembleClassifier": [1],
"TreeEnsembleRegressor": [1],
"Unique": [11],
"Unsqueeze": [13, 11],
"Upsample": [9, 7],
"Where": [16],
"Xor": [7],
"ZipMap": [1],
}
# Manual specification of attribute type.
special_attr_types = dict([("Cast.to", "type")])
# Manual specification of attribute order:
# The names in each tuple will be ordered in that sequence.
special_attr_order = {
("then_branch", "else_branch"),
}
# Special operation importing handlers.
special_op_handler = dict(
[
("BatchNormalization", "ImportNodeBatchNormalization"),
("CategoryMapper", "ImportCategoryMapper"),
("Dropout", "ImportNodeDropout"),
("Cast", "ImportNodeCast"),
("MaxPool", "ImportNodeMaxPool"),
("Pad", "ImportNodePad"),
("Slice", "ImportNodeSlice"),
]
)
# Operations with custom assembly format (alphabetical order).
OpsWithCustomAssemblyFormat = [
"Constant",
"ConstantOfShape",
]
# Operations supporting canonicalization (alphabetical order).
OpsWithCanonicalizer = [
"Add",
"And",
"Cast",
"Constant",
"DepthToSpace",
"DequantizeLinear",
"Div",
"Dropout",
"Equal",
"GlobalAveragePool",
"GlobalMaxPool",
"Greater",
"GRU",
"Identity",
"Less",
"Loop",
"LSTM",
"Mul",
"Or",
"Pow",
"Reshape",
"Resize",
"RNN",
"Shape",
"Size",
"SoftmaxV11",
"SpaceToDepth",
"Squeeze",
"SqueezeV11",
"Sub",
"Tile",
"Transpose",
"Unsqueeze",
"UnsqueezeV11",
"Where",
"Xor",
]
# Operations with custom verifiers (alphabetical order).
OpsWithVerifier = [
"Add",
"And",
"ArgMax",
"ArgMin",
"AveragePool",
"BitShift",
"BitwiseAnd",
"BitwiseOr",
"BitwiseXor",
"CategoryMapper",
"Compress",
"Concat",
"ConcatFromSequence",
"ConstantOfShape",
"Conv",
"ConvTranspose",
"DepthToSpace",
"DequantizeLinear",
"Div",
"Einsum",
"Equal",
"Expand",
"Flatten",
"Gather",
"GatherElements",
"GatherND",
"Gelu",
"Greater",
"GreaterOrEqual",
"GroupNormalizationV18",
"Hardmax",
"If",
"IsInf",
"InstanceNormalization",
"LayerNormalization",
"Less",
"LessOrEqual",
"LogSoftmax",
"Max",
"MatMulInteger",
"Mean",
"Min",
"Mod",
"Mul",
"NonMaxSuppression",
"OneHot",
"OneHotEncoder",
"Optional",
"OptionalGetElement",
"OptionalHasElement",
"Or",
"PRelu",
"Pad",
"Pow",
"RandomNormalLike",
"Range",
"Reshape",
"Resize",
"ReverseSequence",
"RoiAlign",
"ScatterElements",
"ScatterND",
"SequenceEmpty",
"SequenceInsert",
"Shape",
"SpaceToDepth",
"Split",
"SplitToSequence",
"Sub",
"Sum",
"TopK",
"Unique",
"Upsample",
"Where",
"Xor",
]
# Op with fold function
OpsWithFolder = ["Constant", "Squeeze", "SqueezeV11"]
# Op with ConstantLike trait
OpsWithConstantLike = ["Constant"]
# Op with Helper functions
# Here the functions are for data flow analysis.
OpsWithHelpers = {
"Loop": """
mlir::Operation::result_range v_final();
mlir::Operation::result_range scan_outputs();
""",
"Scan": """
mlir::Operation::operand_range getVInitial();
mlir::Operation::result_range v_final();
mlir::Operation::operand_range scan_inputs();
mlir::Operation::result_range scan_outputs();
""",
}
# Type inference are usually done with the type string for Op definition.
# This dictionary provides special code for type inference for some Ops.
# The type inference is used only in Builder before constant canonicalization.
OpsWithResultTypeInference = [
"Constant",
"Cast",
"ConstantOfShape",
"If",
"Loop",
"RandomNormal",
"Scan",
]
# Add an Op in this list if the Op needs result type deduction which is required
# when writing declarative rewriting rules. Deduced type is always
# an UnrankedTensorType whose element type is the same as the first operand's
# element type.
#
# Currently, there are only two build methods generated:
# - one with operands and attributes having a separate parameter, and
# - one with operands and attributes having aggregated parameters.
custom_builder_unranked_ops_list = [
"Abs",
"Conv",
"Exp",
"Identity",
"Neg",
"Pad",
"ReduceLogSum",
"ReduceMaxV13",
"ReduceMaxV18",
"ReduceMax",
"ReduceSum",
"ReduceSumSquare",
"ReduceSumV11",
"Softmax",
"Split",
"SplitV13",
"Sqrt",
"Squeeze",
"SqueezeV11",
"Unsqueeze",
"UnsqueezeV11",
]
# Custom builder op list for operations with broadcast; we can deduce the right
# output type, no need to leave it undef as in the above list.
# Ops must have two operands, not one, not three... And there shall be two.
# TODO: handle variadic ops omitted here: Max, Min, Min, Sum.
custom_builder_broadcast_to_same_type_ops_list = [
"Add",
"And",
"Div",
"Mul",
"Or",
"Pow",
"Sub",
"Xor",
]
custom_builder_broadcast_to_bool_ops_list = [
"Equal",
"Greater",
"GreaterOrEqual",
"Less",
"LessOrEqual",
]
custom_builder_broadcast_ops_list = (
custom_builder_broadcast_to_same_type_ops_list
+ custom_builder_broadcast_to_bool_ops_list
)
# Union of both.
custom_builder_ops_list = (
custom_builder_unranked_ops_list + custom_builder_broadcast_ops_list
)
# A dictionary to add any special definition for an operation.
custom_definition_misc = dict(
[
(
"Constant",
""" let builders = [
OpBuilder<(ins "Attribute":$sparse_value, "Attribute":$value), [{
if (value) {
auto tensorType = mlir::cast<TypedAttr>(value).getType();
build($_builder, $_state, tensorType, sparse_value, value,
FloatAttr(), ArrayAttr(), IntegerAttr(), ArrayAttr(), StringAttr(), ArrayAttr());
} else {
auto tensorType = mlir::cast<TypedAttr>(sparse_value).getType();
build($_builder, $_state, tensorType, sparse_value, value,
FloatAttr(), ArrayAttr(), IntegerAttr(), ArrayAttr(), StringAttr(), ArrayAttr());
}
}]>
];""",
),
(
"Cast",
""" let builders = [
OpBuilder<(ins "Value":$input, "IntegerAttr":$saturate, "TypeAttr":$to), [{
auto resultType = mlir::UnrankedTensorType::get(to.getValue());
build($_builder, $_state, resultType, input, saturate, to);
}] >
];""",
),
]
)
# Get this order from TensorProto in https://github.com/onnx/onnx/blob/main/onnx/onnx.in.proto#L481.
# enum DataType {
# UNDEFINED = 0;
# // Basic types.
# FLOAT = 1; // float
# UINT8 = 2; // uint8_t
# INT8 = 3; // int8_t
# UINT16 = 4; // uint16_t
# INT16 = 5; // int16_t
# INT32 = 6; // int32_t
# INT64 = 7; // int64_t
# STRING = 8; // string
# BOOL = 9; // bool
#
# // IEEE754 half-precision floating-point format (16 bits wide).
# // This format has 1 sign bit, 5 exponent bits, and 10 mantissa bits.
# FLOAT16 = 10;
#
# DOUBLE = 11;
# UINT32 = 12;
# UINT64 = 13;
# COMPLEX64 = 14; // complex with float32 real and imaginary components
# COMPLEX128 = 15; // complex with float64 real and imaginary components
#
# // Non-IEEE floating-point format based on IEEE754 single-precision
# // floating-point number truncated to 16 bits.
# // This format has 1 sign bit, 8 exponent bits, and 7 mantissa bits.
# BFLOAT16 = 16;
#
# // Non-IEEE floating-point format based on papers
# // FP8 Formats for Deep Learning, https://arxiv.org/abs/2209.05433,
# // 8-bit Numerical Formats For Deep Neural Networks, https://arxiv.org/pdf/2206.02915.pdf.
# // Operators supported FP8 are Cast, CastLike, QuantizeLinear, DequantizeLinear.
# // The computation usually happens inside a block quantize / dequantize
# // fused by the runtime.
# FLOAT8E4M3FN = 17; // float 8, mostly used for coefficients, supports nan, not inf
# FLOAT8E4M3FNUZ = 18; // float 8, mostly used for coefficients, supports nan, not inf, no negative zero
# FLOAT8E5M2 = 19; // follows IEEE 754, supports nan, inf, mostly used for gradients
# FLOAT8E5M2FNUZ = 20; // follows IEEE 754, supports nan, inf, mostly used for gradients, no negative zero
#
# // Future extensions go here.
# }
onnx_types = (
"undefined",
"float",
"uint8",
"int8",
"uint16",
"int16",
"int32",
"int64",
"string",
"bool",
"float16",
"double",
"uint32",
"uint64",
"complex64",
"complex128",
"bfloat16",
"float8e4m3fn",
"float8e4m3fnuz",
"float8e5m2",
"float8e5m2fnuz",
)
tblgen_types = (
"BF16",
"F32",
"AnyUI8",
"AnyI8",
"AnyUI16",
"AnyI16",
"AnyI32",
"AnyI64",
"StringType",
"AnyI1",
"F16",
"F64",
"AnyUI32",
"AnyUI64",
"Complex<F32>",
"Complex<F64>",
"BF16",
"F8E4M3FN",
"F8E4M3FNUZ",
"F8E5M2",
"F8E5M2FNUZ",
)
# Maximum count for actual type. Number more than MAX_NUM_TYPES will be used to encode
# the mapping method. MAX_NUM_TYPES should be greater than the length of onnx_types
# This value has to be kept the same with MAX_TYPE in FrontendDialectTransformer.cpp
MAX_NUM_TYPES = 30
# Attribute names are ordered alphabetically except for the
# manually specified special orderings in special_attr_order.
def order_attr_names(attrNames):
attrNames = sorted(attrNames)
for namesOrder in special_attr_order:
# If attrNames includes all the namesOrder names, then reorder
# those names in attrNames to their order in namesOrder,
if set(namesOrder).issubset(attrNames):
# The namesIndexes are where the namesOrder names appear in attrNames.
namesIndexes = (attrNames.index(name) for name in namesOrder)
# Write the namesOrder names into those indexes in the correct order.
for name, index in zip(namesOrder, sorted(namesIndexes)):
attrNames[index] = name
return attrNames
def should_render_domain(domain): # type: (Text) -> bool
return True
def display_attr_type(v): # type: (OpSchema.AttrType) -> Text
assert isinstance(v, OpSchema.AttrType)
s = Text(v)
s = s[s.rfind(".") + 1 :].lower()
if s[-1] == "s":
s = "list of " + s
return s
# ONNX allows input and output to have the same name. But MLIR does not
# When the conflict occurs, add 'out_' to the output name
def get_unique_output_name(schema, name):
for input in schema.inputs:
if input.name == name:
return "out_" + name
return name
def onnx_attr_type_to_mlir_attr_type(t):
onnx_attr_type = Text(t)
onnx_attr_type = onnx_attr_type[onnx_attr_type.rfind(".") + 1 :].lower()
if onnx_attr_type == "int":
mlir_attr_type = "SI64Attr"
elif onnx_attr_type == "float":
mlir_attr_type = "F32Attr"
elif onnx_attr_type == "ints":
mlir_attr_type = "I64ArrayAttr"
elif onnx_attr_type == "floats":
mlir_attr_type = "F32ArrayAttr"
elif onnx_attr_type == "string":
mlir_attr_type = "StrAttr"
elif onnx_attr_type == "strings":
mlir_attr_type = "StrArrayAttr"
elif onnx_attr_type in {"type", "type_proto"}:
# 'type' is the attribute type used in special_attr_types,
# 'type_proto' is Optional op's type attribute's type
mlir_attr_type = "TypeAttr"
else:
mlir_attr_type = "AnyAttr"
# TODO: tensor and sparse tensor.
return mlir_attr_type
# TODO: any better way to do this.
def tblgen_attr_type_to_cpp_type(t):
if "I64Attr" in t:
cpp_type = "IntegerAttr"
elif "F32Attr" in t:
cpp_type = "FloatAttr"
elif "I64ArrayAttr" in t or "F32ArrayAttr" in t:
cpp_type = "ArrayAttr"
elif "StrAttr" in t:
cpp_type = "StringAttr"
elif "strings" in t:
cpp_type = "ArrayAttr"
else:
cpp_type = "Attribute"
return cpp_type
def tblgen_operand_type_to_cpp_type(op_type):
if op_type.startswith("Variadic"):
mytype = "ValueRange"
else:
mytype = "Value"
return mytype
def np_type_to_tblgen_attr_type(tstr):
index = -1
for i in range(len(onnx_types)):
if onnx_types[i] in tstr:
index = i
break
if index == -1:
return None
else:
return tblgen_types[i]
def get_tblgen_type_index(type_str):
return tblgen_types.index(type_str)
# The possible data structures are tensor, map and seq(tensor()).
def get_data_structure_element(allowed_type_str):
structure_list = ["tensor", "seq", "map"]
for structure in structure_list:
if allowed_type_str.startswith(structure):
element = allowed_type_str.replace(structure + "(", "", 1).replace(
")", "", 1
)
return (structure, element)
return (None, None)
def get_allowed_elem_types(schema, input):
# allowed_types_str = None
# return allowed_types_str
# TODO: enable type constraints.
if input.type_str:
tstr = input.type_str
structure, element = get_data_structure_element(tstr)
# In case the type is directly specified.
if structure and element:
t = np_type_to_tblgen_attr_type(element)
if t == None:
return allowed_structure, None
else:
return structure, [t]
else:
return None
if schema.type_constraints:
for type_constraint in schema.type_constraints:
if type_constraint.type_param_str != tstr:
continue
allowed_type_list = []
allowedTypes = type_constraint.allowed_type_strs
allowed_structure = None
for allowedType in allowedTypes:
structure, element = get_data_structure_element(allowedType)
if structure == None or element == None:
return None, None
if allowed_structure != None and allowed_structure != structure:
return None, None
allowed_structure = structure
t = np_type_to_tblgen_attr_type(element)
if t == None:
return allowed_structure, None
if not t in allowed_type_list:
allowed_type_list.append(t)
return allowed_structure, allowed_type_list
return None, None
def inc_indent(indent=None):
return "" if indent is None else indent + " " * 2
def dec_indent(indent):
return indent[:-2]
def join_args(args):
return ", ".join(args)
def get_operands_or_results(schema, type_str_dict, op_name, is_input):
value_list = schema.inputs if is_input else schema.outputs
if not value_list:
return OrderedDict()
def any_type_of(types):
assert isinstance(types, list)
if len(types) == 1:
return types[0]
else:
return "AnyTypeOf<[{}]>".format(", ".join(types))
name_to_types = OrderedDict()
for i, value in enumerate(value_list):
str_types = get_onnx_mlir_types(schema, type_str_dict, value)
# In case the type string is used more than once.
types = str_types.copy()
# No need to add AnyMemRef type. Keep the code in case.
# types.append("AnyMemRef")
if OpSchema.FormalParameterOption.Optional == value.option:
types.append("NoneType")
if OpSchema.FormalParameterOption.Variadic == value.option:
if value.is_homogeneous:
types = ["Variadic<{}>".format(any_type_of(types))]
else:
# TODO handle(variadic, heterogeneous) "
types = ["Variadic<{}>".format(any_type_of(types))]
sys.stderr.write(
"warning: (variadic, heterogeneous) for "
+ schema.name
+ " "
+ value.name
+ "\n"
)
# Since output name can coincide with that of an input, we explicitly
# append a suffix "_out" to such names for disambiguation.
if is_input:
value_name = value.name
else:
value_name = get_unique_output_name(schema, value.name)
name_to_types[value_name] = any_type_of(types)
return name_to_types
def get_attrs(schema):
def get_attr_type_optional(attr_type):
return "OptionalAttr<{}>".format(onnx_attr_type_to_mlir_attr_type(attr_type))
def get_attr_type_with_default(attr_type, attr_default):
if attr_type == OpSchema.AttrType.STRING:
return 'DefaultValuedStrAttr<{}, "{}">'.format(
onnx_attr_type_to_mlir_attr_type(attr_type), attr_default
)
else:
return 'DefaultValuedAttr<{}, "{}">'.format(
onnx_attr_type_to_mlir_attr_type(attr_type), attr_default
)
if not schema.attributes:
return OrderedDict()
name_to_type = OrderedDict()
for _, attr in sorted(schema.attributes.items()):
if attr.type == OpSchema.AttrType.GRAPH:
continue
qualified_attr_name = "{}.{}".format(schema.name, attr.name)
if qualified_attr_name in special_attr_types:
name_to_type[attr.name] = onnx_attr_type_to_mlir_attr_type(
special_attr_types[qualified_attr_name]
)
# Option holds either required or default value.
elif attr.required:
name_to_type[attr.name] = onnx_attr_type_to_mlir_attr_type(attr.type)
elif attr.default_value.name:
def format_value(value): # type: (Any) -> Text
if isinstance(value, float):
formatted = str(np.round(value, 5))
# Use default formatting, unless too long.
if len(formatted) > 10:
formatted = str("({:e})".format(value))
return formatted
elif isinstance(value, (bytes, bytearray)) and sys.version_info[0] == 3:
return str(value.decode("utf-8"))
return str(value)
default_value = helper.get_attribute_value(attr.default_value)
if isinstance(default_value, list):
default_value = [format_value(val) for val in default_value]
default_value_str = "{}".format(default_value)
default_value_str = default_value_str.replace("[", "{", 1)
default_value_str = default_value_str.replace("]", "}", 1)
if Text(attr.type) == "AttrType.STRINGS":
default_value_str = default_value_str.replace("'", '\\"')
else:
default_value_str = default_value_str.replace("'", "")
else:
default_value = format_value(default_value)
default_value_str = default_value
name_to_type[attr.name] = get_attr_type_with_default(
attr.type, default_value_str
)
else:
name_to_type[attr.name] = get_attr_type_optional(attr.type)
return name_to_type
def get_numberof_list(my_list):
expected_num = len(my_list)
for element in my_list:
if OpSchema.FormalParameterOption.Variadic == element.option:
expected_num = -1
return expected_num
def get_output_type_mapping(schema):
mapping = []
for output in schema.outputs:
# If only one type is allowed, just set that.
structure, allowed_elem_types = get_allowed_elem_types(schema, output)
if allowed_elem_types != None and len(allowed_elem_types) == 1:
mapping.append(str(get_tblgen_type_index(allowed_elem_types[0])))
continue
# Map the type string.
if output.type_str:
tstr = output.type_str
found = False
for i, input in enumerate(schema.inputs):
if input.type_str and input.type_str == tstr:
mapping.append(str(i + MAX_NUM_TYPES))
found = True
break
if found:
continue
# Unknown output type.
mapping.append(str(-1))
return mapping
def get_numberof_inout(s, indent, schema):
expected_num_operands = get_numberof_list(schema.inputs)
indent = inc_indent(indent)
s += indent + "static int getNumberOfOperands() {\n"
indent = inc_indent(indent)
s += indent + "return {};\n".format(expected_num_operands)
indent = dec_indent(indent)
s += indent + "}\n"
expected_num_results = get_numberof_list(schema.outputs)
s += indent + "static int getNumberOfResults() {\n"
indent = inc_indent(indent)