/
tfl_ops.td
4335 lines (3458 loc) · 138 KB
/
tfl_ops.td
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 2019 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// This is the operation definition file for TensorFlow Lite.
#ifndef TFL_OPS
#define TFL_OPS
include "mlir/IR/OpBase.td"
include "mlir/Interfaces/LoopLikeInterface.td"
include "mlir/Interfaces/SideEffectInterfaces.td"
include "tensorflow/compiler/mlir/lite/ir/tfl_op_interfaces.td"
include "tensorflow/compiler/mlir/lite/quantization/quantization.td"
def TFL_Dialect : Dialect {
let name = "tfl";
let description = [{
The TensorFlow Lite dialect.
This dialect maps to TensorFlow Lite operations.
Invariants:
* All values are of Tensor type (in particular, scalars are
represented using zero-dimensional tensors);
}];
let cppNamespace = "TFL";
}
//===----------------------------------------------------------------------===//
// TFLite dialect string type - uses the TF string type as implementation
//===----------------------------------------------------------------------===//
def TFL_Str : Type<CPred<"$_self.isa<mlir::TF::StringType>()">,
"TFLite string type">,
BuildableType<"getType<mlir::TF::StringType>()">;
//===----------------------------------------------------------------------===//
// TFLite dialect quint8 type - uses the TF quint8 type as implementation
//===----------------------------------------------------------------------===//
def TFL_Quint8 : Type<CPred<"$_self.isa<mlir::TF::Quint8Type>()">,
"TFLite quint8 type">,
BuildableType<"getType<mlir::TF::Quint8Type>()">;
//===----------------------------------------------------------------------===//
// Activation function enum definitions.
//===----------------------------------------------------------------------===//
// Allowed activation function cases
// These should match the ActivationFunctionType enum in TFLite schema.
def TFL_AF_None : StrEnumAttrCase<"NONE">;
def TFL_AF_Relu : StrEnumAttrCase<"RELU">;
def TFL_AF_Relu1 : StrEnumAttrCase<"RELU_N1_TO_1">;
def TFL_AF_Relu6 : StrEnumAttrCase<"RELU6">;
def TFL_AF_Tanh : StrEnumAttrCase<"TANH">;
def TFL_AF_Sign : StrEnumAttrCase<"SIGN_BIT">;
def TFL_AFAttr : StrEnumAttr<
"ActivationFunctionType", "fused activation enum", [
TFL_AF_None, TFL_AF_Relu, TFL_AF_Relu1,
TFL_AF_Relu6, TFL_AF_Tanh, TFL_AF_Sign
]>;
//===----------------------------------------------------------------------===//
// Padding enum definitions.
//===----------------------------------------------------------------------===//
// Allowed padding cases
// These should match the padding enum in TFLite schema.
def TFL_PAD_Same : StrEnumAttrCase<"SAME">;
def TFL_PAD_Valid : StrEnumAttrCase<"VALID">;
def TFL_MIRRORPAD_Reflect : StrEnumAttrCase<"REFLECT">;
def TFL_MIRRORPAD_Symmetric : StrEnumAttrCase<"SYMMETRIC">;
def TFL_PaddingAttr : StrEnumAttr<"Padding", "padding enum", [
TFL_PAD_Same, TFL_PAD_Valid
]>;
def TFL_MirrorPaddingAttr : StrEnumAttr<"Padding", "Mirror pad enum", [
TFL_MIRRORPAD_Reflect, TFL_MIRRORPAD_Symmetric
]>;
//===----------------------------------------------------------------------===//
// TensorType attribute definitions.
//===----------------------------------------------------------------------===//
// A type attribute containing the TensorType.
def TensorTypeAttr : TypeAttrBase<"TensorType", "Tensor type attribute">;
// A type attribute containing OpaqueElementsAttr and bytes.
def OpaqueBytesAttr : ElementsAttrBase<
And<[
CPred<"$_self.isa<OpaqueElementsAttr>() ">,
CPred<"$_self.cast<OpaqueElementsAttr>().getType()"
".getElementType().isInteger(8)">,
]>,
"opaque bytes attribute"
>;
//===----------------------------------------------------------------------===//
// Derived shape attribute class.
//===----------------------------------------------------------------------===//
class DerivedShapeAttr<code body> : DerivedAttr<"ArrayRef<int64_t>", body>;
class DerivedTFLiteTypeAttr<code body, code convert> :
DerivedAttr<"tflite::TensorType", body, convert>;
// TFL Runtime op trait predicate.
class TFL_RuntimePredOpTrait<string desc, Pred pred> :
GenInternalOpTrait<"TFLRuntimeOpTrait"> {
Pred tflRuntimePredicate = pred;
string tflRuntimeDescription = desc;
}
class TFL_OperandsHaveSameShapesOrBroadcastableShape<
list<int> indices, int max_bcast_rank> :
TFL_RuntimePredOpTrait<"operands do not have the same shape or "
"broadcastable shapes within the rank " # max_bcast_rank,
CPred<"TFL::VerifyOperandsHaveSameShapesOrBroadcastableShape("
"$_op, llvm::ArrayRef<unsigned>({" # StrJoinInt<indices>.result #
"}), " # max_bcast_rank # ")">>;
// These additional types/type constraints here are used to decouple the ops
// from runtime support for the ops. Prefer to use these types when defining
// new TF_Ops for uniformity.
// TFL Runtime type predicate.
class TFL_RuntimeType<TypeConstraint t> {
Pred tflRuntimeTypePredicate = t.predicate;
string tflRuntimeTypeDescription = t.description;
}
class TFL_AnyTypeOf<list<Type> allowedRuntimeTypes, string description = "",
list<Type> allowedOpTypes = [AnyType]> :
AnyTypeOf<allowedOpTypes, description>,
TFL_RuntimeType<AnyTypeOf<allowedRuntimeTypes, description>>;
class TFL_TensorOf<list<Type> allowedRuntimeTypes,
list<Type> allowedOpTypes = [AnyType]> :
TensorOf<allowedOpTypes>, TFL_RuntimeType<TensorOf<allowedRuntimeTypes>>;
class TFL_TensorOfOrNone<list<Type> allowedRuntimeTypes, string description = "",
list<Type> allowedOpTypes = [AnyType]> :
AnyTypeOf<[TFL_TensorOf<allowedOpTypes>, NoneType], description>,
TFL_RuntimeType<AnyTypeOf<[TFL_TensorOf<allowedRuntimeTypes>, NoneType]>>;
class TFL_VariadicTensorOf<list<Type> allowedRuntimeTypes,
list<Type> allowedOpTypes = [AnyType]> :
Variadic<TensorOf<allowedOpTypes>>,
TFL_RuntimeType<Variadic<TensorOf<allowedRuntimeTypes>>>;
def TFL_Int32Or64 : SignlessIntOfWidths<[32, 64]>;
def TFL_BoolTensor : TFL_TensorOf<[I1]>;
def TFL_FpTensor : TFL_TensorOf<[F32]>;
def TFL_I32OrI64Tensor : TFL_TensorOf<[TFL_Int32Or64]>;
def TFL_I32Tensor : TFL_TensorOf<[I32]>;
def TFL_I64Tensor : TFL_TensorOf<[I64]>;
// TODO(jpienaar): Expand to all int types.
def TFL_IntTensor : TypeAlias<TFL_I32Tensor, "tensor of any integer type">;
class TFL_0DTensorOf<list<Type> allowedRuntimeTypes,
list<Type> allowedOpTypes = [AnyType]> :
0DTensorOf<allowedOpTypes>, TFL_RuntimeType<TensorOf<allowedRuntimeTypes>>;
class TFL_1DTensorOf<list<Type> allowedRuntimeTypes,
list<Type> allowedOpTypes = [AnyType]> :
1DTensorOf<allowedOpTypes>, TFL_RuntimeType<TensorOf<allowedRuntimeTypes>>;
class TFL_2DTensorOf<list<Type> allowedRuntimeTypes,
list<Type> allowedOpTypes = [AnyType]> :
2DTensorOf<allowedOpTypes>, TFL_RuntimeType<TensorOf<allowedRuntimeTypes>>;
// This is used to represent the type of "ref tensors" or tensors that are
// used as variables to track state.
def TFL_StatefulTensor : TypeAlias<AnyTensor, "stateful tensor">;
//===----------------------------------------------------------------------===//
// Rank/Shape helpers.
//===----------------------------------------------------------------------===//
class TFL_OperandIsUnrankedPred<int n> :
CPred<"$_op.getOperand(" # n # ").getType().isa<UnrankedTensorType>()">;
// TODO: Some of these could be generalized and/or moved to more general
// location.
// Returns true if the n-th operand has unknown rank or has rank m.
class TFL_OperandHasRank<int n, int m> :
PredOpTrait<"operand " # n # " is " # m # "-D",
Or<[TFL_OperandIsUnrankedPred<n>,
CPred<"$_op.getOperand(" # n #
").getType().cast<ShapedType>().getRank() == " # m>]>>;
// Returns true if the n-th operand is ranked and has rank dim.
class TFL_OperandHasKnownRank<int n, int dim> : And<[
CPred<"$_op.getOperand(" # n # ").getType().isa<RankedTensorType>()">,
CPred<"$_op.getOperand(" # n # ").getType().cast<ShapedType>().getRank() == "
# dim>]>;
// True if operand n is ranked and has a rank > dim.
class TFL_OperandIsRankedAndHasDimPred<int n, int dim> : And<[
CPred<"$_op.getOperand(" # n # ").getType().isa<RankedTensorType>()">,
CPred<"$_op.getOperand(" # n # ").getType().cast<ShapedType>().getRank() > "
# dim>]>;
// Returns true if the n-th operand is ranked and has a dimension length = size
// at the rank dim.
class TFL_OperandDimEquals<int n, int dim, int size> : And<[
TFL_OperandIsRankedAndHasDimPred<n, dim>,
CPred<"$_op.getOperand(" # n # ").getType().cast<ShapedType>()"
".getShape()[" # dim # " ] == " # size>]>;
// Returns true if the n-th operand is ranked and has a dimension length <=
// size at the rank dim.
class TFL_OperandDimIsAtMost<int n, int dim, int size> : And<[
TFL_OperandIsRankedAndHasDimPred<n, dim>,
CPred<"$_op.getOperand(" # n # ").getType().cast<ShapedType>()"
".getShape()[" # dim # " ] <= " # size>]>;
// Returns true if the n-th operand has unknown rank or at least rank m.
class TFL_OperandHasAtleastRank<int n, int m> :
PredOpTrait<"operand " # n # " is " # m # "-D",
Or<[CPred<"$_op.getOperand(" # n # ").getType().isa<UnrankedTensorType>()">,
CPred<"$_op.getOperand(" # n #
").getType().cast<ShapedType>().getRank() >= " # m>]>>;
class TFL_OperandRankEquals1DimOfOperand<int x, int y> :
PredOpTrait<"operand " # x # "'s rank equals operand " # y # "'s size",
Or<[TFL_OperandIsUnrankedPred<x>,
TFL_OperandIsUnrankedPred<y>,
CPred<"!$_op.getOperand(" # y #
").getType().cast<ShapedType>().hasStaticShape()">,
CPred<"$_op.getOperand(" # x #
").getType().cast<ShapedType>().getRank() == "
"$_op.getOperand(" # y #
").getType().cast<ShapedType>().getShape()[0]">]>>;
class TFL_Operand0DOr1ElementTensor<int x> :
PredOpTrait<"operand #" # x # " is an 0-d tensor or 1-d tensor w/ 1 element",
Or<[TFL_OperandHasKnownRank<x, 0>,
And<[TFL_OperandHasKnownRank<x, 1>, TFL_OperandDimEquals<x, 0, 1>]>]>>;
// tf.uint8 and tf.quint8 are mapped to the same tflite types, so they are equal
// when used as element types.
class TFL_TFTypesWithSameBits<int i, int j, int num> :
And<[
Or<[CPred<"getElementTypeOrSelf($_op.getResult(" # i # ")).isa<mlir::TF::Quint" # num # "Type>()">,
CPred<"getElementTypeOrSelf($_op.getResult(" # i # ")).isUnsignedInteger(" # num # ")">]>,
Or<[CPred<"getElementTypeOrSelf($_op.getOperand(" # j # ")).isa<mlir::TF::Quint" # num # "Type>()">,
CPred<"getElementTypeOrSelf($_op.getOperand(" # j # ")).isUnsignedInteger(" # num # ")">]>]>;
class TFL_TFOperandTypesWithSameBits<int i, int j, int num> :
And<[
Or<[CPred<"getElementTypeOrSelf($_op.getOperand(" # i # ")).isa<mlir::TF::Quint" # num # "Type>()">,
CPred<"getElementTypeOrSelf($_op.getOperand(" # i # ")).isUnsignedInteger(" # num # ")">]>,
Or<[CPred<"getElementTypeOrSelf($_op.getOperand(" # j # ")).isa<mlir::TF::Quint" # num # "Type>()">,
CPred<"getElementTypeOrSelf($_op.getOperand(" # j # ")).isUnsignedInteger(" # num # ")">]>]>;
class TFL_OperandIsNoneOrHasRank<int n, int m> :
PredOpTrait<"operand " # n # " is " # m # "-D",
Or<[
CPred<"$_op.getOperand(" # n # ").getType().isa<NoneType>()">,
TFL_OperandIsUnrankedPred<n>,
CPred<"$_op.getOperand(" # n #
").getType().cast<ShapedType>().getRank() == " # m>]>>;
class TFL_OperandIsNoneOrHasRankAtMost<int n, int m> :
PredOpTrait<"operand " # n # " is at most " # m # "-D",
Or<[
CPred<"$_op.getOperand(" # n # ").getType().isa<NoneType>()">,
TFL_OperandIsUnrankedPred<n>,
CPred<"$_op.getOperand(" # n #
").getType().cast<ShapedType>().getRank() <= " # m>]>>;
class TFL_OperandHasRankAtMost<int n, int m> :
PredOpTrait<"operand " # n # " is at most " # m # "-D",
Or<[TFL_OperandIsUnrankedPred<n>,
CPred<"$_op.getOperand(" # n #
").getType().cast<ShapedType>().getRank() <= " # m>]>>;
class TFL_OperandHasRankAtLeast<int n, int m> :
PredOpTrait<"operand " # n # " is at least " # m # "-D",
Or<[TFL_OperandIsUnrankedPred<n>,
CPred<"$_op.getOperand(" # n #
").getType().cast<ShapedType>().getRank() >= " # m>]>>;
class TFL_OperandHasRankRange<int n, int x, int y> :
PredOpTrait<"operand " # n # " has rank range [" # x # ", " # y # "]",
Or<[TFL_OperandIsUnrankedPred<n>,
CPred<"$_op.getOperand(" # n # ").getType().cast<ShapedType>().getRank() "
">= " # x # " && $_op.getOperand(" # n # ").getType().cast<ShapedType>()."
"getRank() <= " # y>]>>;
def TFL_FloatNonNegative : AttrConstraint<
CPred<"$_self.isa<FloatAttr>() && "
"!$_self.cast<FloatAttr>().getValue().isNegative()">,
"whose value is non-negative">;
def TFL_BoolTrue : AttrConstraint<
CPred<"$_self.isa<BoolAttr>() && $_self.cast<BoolAttr>().getValue()">,
"whose value is true">;
def TFL_BoolFalse : AttrConstraint<
CPred<"$_self.isa<BoolAttr>() && !$_self.cast<BoolAttr>().getValue()">,
"whose value is false">;
class TFL_StringEqualsTo<string value> : AttrConstraint<
CPred<"$_self.cast<StringAttr>().getValue() == \"" # value # "\"">,
"whose value equals to '" # value # "'">;
// Ensures the array attribute's size is within the given maximum size.
class TFL_ArrayMaxCount<int n> : AttrConstraint<
CPred<"$_self.isa<ArrayAttr>() && $_self.cast<ArrayAttr>().size() <= " # n>,
"whose size is at most " # n>;
// Ensures the given integer attribute has the given value.
class TFL_IntEqualsTo<int n> : AttrConstraint<
CPred<"$_self.isa<IntegerAttr>() && "
"$_self.cast<IntegerAttr>().getInt() == " # n>,
"whose value is " # n>;
// This is a quantization-aware version of TCresVTEtIsSameAsOp
class TFL_TCresVTEtIsSameAsOp<int i, int j> : And<[
TCOpResIsShapedTypePred<i, j>,
Or<[
TCresVTEtIsSameAsOpBase<i, j>,
TFL_TFTypesWithSameBits<i, j, 8>,
And<[
SubstLeaves<"$_self", "getElementTypeOrSelf($_op.getOperand(" # j # "))",
quant_QuantizedType.predicate>,
CPred<"quant::QuantizedType::castToStorageType("
"getElementTypeOrSelf($_op.getResult(" # i # "))) == "
"quant::QuantizedType::castToStorageType("
"getElementTypeOrSelf($_op.getOperand(" # j # ")))">]>]>]>;
// This is a quantization-aware version of TCresVTEtIsSameAsOp
class TFL_TCopVTEtAreSameAt<int i, int j> : Or<[
TCopVTEtAreSameAt<[i, j]>,
TFL_TFOperandTypesWithSameBits<i, j, 8>,
And<[
SubstLeaves<"$_self", "getElementTypeOrSelf($_op.getOperand(" # j # "))",
quant_QuantizedType.predicate>,
CPred<"quant::QuantizedType::castToStorageType("
"getElementTypeOrSelf($_op.getOperand(" # i # "))) == "
"quant::QuantizedType::castToStorageType("
"getElementTypeOrSelf($_op.getOperand(" # j # ")))">]>]>;
//===----------------------------------------------------------------------===//
// TFL op common constraints.
//===----------------------------------------------------------------------===//
// This is a constraint for most of the binary ops, e.g., add, mul, div, etc.
// Binary ops lhs & rhs should have the same value type, and is capable to
// compare quantiziation types as well.
def BinaryOpSameElementTypeConstraint :
PredOpTrait<"operands have same element type",
Or<[
TCopVTEtIsSameAs<0, 1>,
// Two operands' values are both quantized and their type have the same
// underlying storage type.
And<[
SubstLeaves<"$_self", "getElementTypeOrSelf($_op.getOperand(0))",
quant_QuantizedType.predicate>,
CPred<"quant::QuantizedType::castToStorageType("
"getElementTypeOrSelf($_op.getOperand(0))) == "
"quant::QuantizedType::castToStorageType("
"getElementTypeOrSelf($_op.getOperand(1)))">]>]>>;
//===----------------------------------------------------------------------===//
// TFL common builders.
//===----------------------------------------------------------------------===//
def TFL_BroadcastableBinaryBuilder : OpBuilder<
"OpBuilder &builder, OperationState &result, Value lhs, Value rhs",
[{
auto resultType =
OpTrait::util::getBroadcastedType(lhs.getType(), rhs.getType());
if (!resultType)
mlir::emitError(result.location, "non-broadcastable operands");
result.addOperands({lhs, rhs});
result.types.push_back(resultType);
}]>;
def TFL_FusedBroadcastableBinaryBuilder : OpBuilder<
"OpBuilder &builder, OperationState &result, Value lhs, Value rhs, "
"StringAttr fusedActivationFunction",
[{
buildFusedBroadcastableBinOp(
&builder, result, lhs, rhs, fusedActivationFunction);
}]>;
def TFL_ComparisonBinaryBuilder : OpBuilder<
"OpBuilder &builder, OperationState &result, Value lhs, Value rhs",
[{
buildComparisonBinOp(&builder, result, lhs, rhs);
}]>;
//===----------------------------------------------------------------------===//
// TFL op base class.
//===----------------------------------------------------------------------===//
class TFL_Op<string mnemonic, list<OpTrait> traits = []> :
Op<TFL_Dialect, mnemonic, !listconcat(traits,
[DeclareOpInterfaceMethods<TFL_RuntimeVerification>,
// All TFL ops are supported on CPU.
DeclareOpInterfaceMethods<TFL_CpuTargetOp>
])> {
// FlatBuffer generation specific information.
// -------------------------------------------
// When generating the FlatBuffer output some operations have
// Options (as defined in the schema). These options are effectively
// the attributes of the operations (e.g., what padding is to be used
// for a pooling operator). Not all operations have Options and some
// operations share Options. The following attributes indicate whether
// the operation has Options in the serialized FlatBuffer.
// Whether the TFLite operator has options in the schema representation.
bit hasOptions = 0b0;
// Use to specify a custom options type for TFLite operators where
// the option's name does not match the TFLite operator's name.
// If no customOption is specified then <name>Options is used if the op
// hasOptions.
string customOption = ?;
}
class TFL_ConvOp<string mnemonic, string opSummary, int index> :
TFL_Op<mnemonic, [NoSideEffect, AccumulatorUniformScale<2, 0, 1>,
TFL_ChannelDimIndexInterface, AffineOpCoefficient<index, 1>,
TFL_GpuTargetOp, TFL_SparseOp]> {
let summary = opSummary # " operator";
let description = [{
Performs convolution operation on inputs.
Inputs:
`inputs[0]`: required: the input activation tensor
`inputs[1]`: required: the filter weight tensor
`inputs[2]`: optional: the bias tensor
}];
let arguments = (
ins TFL_TensorOf<[F32, QI8, QUI8, QI16]>:$input,
TFL_TensorOf<[F32, QI8, QUI8]>:$filter,
TFL_TensorOfOrNone<[F32, I32, I64]>:$bias,
I32Attr:$dilation_h_factor,
I32Attr:$dilation_w_factor,
TFL_AFAttr:$fused_activation_function,
TFL_PaddingAttr:$padding,
I32Attr:$stride_h,
I32Attr:$stride_w
);
let results = (outs TFL_TensorOf<[F32, QI8, QUI8, QI16]>:$output);
let hasOptions = 0b1;
}
//===----------------------------------------------------------------------===//
// TFL op definitions.
//===----------------------------------------------------------------------===//
def TFL_AbsOp : TFL_Op<"abs", [
NoSideEffect,
SameOperandsAndResultShape,
SameOperandsAndResultType,
NoQuantizableResult,
TFL_GpuTargetOp]> {
let summary = "Absolute value operator";
let description = [{
Given a tensor `x`, this operation returns a tensor containing the absolute
value of each element in `x`. For example, if x is an input element and y is
an output element, this operation computes \\(y = |x|\\).
}];
let arguments = (ins TFL_FpTensor:$x);
let results = (outs TFL_FpTensor:$y);
let hasFolder = 1;
}
def TFL_AddOp : TFL_Op<"add", [
TFL_RuntimePredOpTrait<"Operands do not have valid shapes",
CPred<"TFL::VerifyAddOpShapeConstraints(llvm::cast<AddOp>($_op))">>,
ResultsBroadcastableShape,
NoSideEffect,
Commutative,
TFL_GpuTargetOp]> {
let summary = "Addition operator";
let description = [{
Element-wise addition operation.
}];
let arguments = (
ins TFL_TensorOf<[F32, I32, QI8, QUI8, QI16]>:$lhs,
TFL_TensorOf<[F32, I32, QI8, QUI8, QI16]>:$rhs,
TFL_AFAttr:$fused_activation_function);
let results = (outs TFL_TensorOf<[F32, I32, QI8, QUI8, QI16]>:$output);
let hasFolder = 1;
let builders = [TFL_FusedBroadcastableBinaryBuilder];
let parser = [{ return mlir::impl::parseOneResultSameOperandTypeOp(parser, result); }];
let printer = [{ return mlir::impl::printOneResultOp(getOperation(), p); }];
let hasOptions = 1;
}
def TFL_AddNOp : TFL_Op<"add_n", [Commutative, NoSideEffect, SameOperandsAndResultsScale]> {
let summary = "add_n operator";
let description = [{
Adds all input tensors element-wise.
}];
let arguments = (ins
TFL_VariadicTensorOf<[F32, I32]>:$inputs
);
let results = (outs
TFL_TensorOf<[F32, I32]>:$sum
);
}
def TFL_ReduceAnyOp : TFL_Op<"reduce_any", [NoSideEffect]> {
let summary = [{
Computes the "logical or" of elements across dimensions of a tensor.
}];
let description = [{
Reduces `input` along the dimensions given in `axis`. Unless
`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in
`axis`. If `keep_dims` is true, the reduced dimensions are
retained with length 1.
}];
let arguments = (ins
TFL_BoolTensor:$input,
TFL_I32Tensor:$reduction_indices,
DefaultValuedAttr<BoolAttr, "false">:$keep_dims
);
let results = (outs
TFL_BoolTensor:$output
);
let hasOptions = 1;
let customOption = "ReducerOptions";
}
def TFL_TransposeConvOp: TFL_Op<"transpose_conv", [
NoSideEffect,
TFL_OperandHasRank<0, 1>,
TFL_OperandHasRank<1, 4>,
TFL_OperandHasRank<2, 4>,
PredOpTrait<"input and output must have same element type",
TFL_TCresVTEtIsSameAsOp<0, 2>>,
AccumulatorUniformScale<3, 1, 2>,
TFL_ChannelDimIndexInterface, AffineOpCoefficient<0, 2>,
TFL_GpuTargetOp,
TFL_SparseOp]> {
let summary = "Transpose convolution operator";
let description = [{
Performs transpose convolution operation on input.
}];
let arguments = (ins
TFL_I32Tensor:$output_shape,
TFL_TensorOf<[F32, QI8, QUI8]>:$weights,
TFL_TensorOf<[F32, QI8, QUI8]>:$input,
TFL_TensorOfOrNone<[F32, QI32]>:$bias,
TFL_PaddingAttr:$padding,
Confined<I32Attr, [IntPositive]>:$stride_h,
Confined<I32Attr, [IntPositive]>:$stride_w
);
let results = (outs TFL_TensorOf<[F32, QI8, QUI8]>:$output);
let hasOptions = 1;
let verifier = [{ return Verify(*this); }];
let extraClassDeclaration = [{
// ChannelDimIndexInterface:
int GetChannelDimIndex() { return 0; }
// SparseOpInterface:
std::vector<int> GetSparseOperands() { return {1}; }
std::vector<std::vector<int>> GetFloatBlockSize() { return {}; }
std::vector<std::vector<int>> GetQuantizedBlockSize() { return {}; }
}];
}
def TFL_AveragePool2DOp:
TFL_Op<"average_pool_2d",
[NoSideEffect,
SameOperandsAndResultsScale,
TFL_GpuTargetOp]> {
let summary = "Average_pool_2d operator";
let description = [{
Performs average-pooling operation on input.
}];
let arguments = (
ins TFL_TensorOf<[F32, QI8, QUI8]>:$input,
I32Attr:$filter_height,
I32Attr:$filter_width,
TFL_PaddingAttr:$padding,
I32Attr:$stride_h,
I32Attr:$stride_w,
TFL_AFAttr:$fused_activation_function
);
let results = (outs TFL_TensorOf<[F32, QI8, QUI8]>:$output);
let hasOptions = 1;
let customOption = "Pool2DOptions";
}
def TFL_ArgMaxOp : TFL_Op<"arg_max", [NoSideEffect]> {
let summary = "ArgMax operator";
let description = [{
Returns the index with the largest value across dimensions of a tensor.
}];
let arguments = (
ins TFL_TensorOf<[F32, I32, I8, UI8, QI8, QUI8]>:$input,
TFL_I32OrI64Tensor:$dim
);
let results = (outs
TFL_I32OrI64Tensor:$output
);
let hasOptions = 1;
DerivedTFLiteTypeAttr output_type = DerivedTFLiteTypeAttr<[{
return getResult().getType().cast<TensorType>().getElementType().
cast<IntegerType>().getWidth() > 32 ? tflite::TensorType_INT64 :
tflite::TensorType_INT32;
}], [{
TypeAttr::get(getResult().getType().cast<TensorType>().getElementType())
}]>;
}
def TFL_ArgMinOp : TFL_Op<"arg_min", [NoSideEffect]> {
let summary = "ArgMin operator";
let description = [{
Returns the index with the smallest value across dimensions of a tensor.
a = [1, 10, 26.9, 2.8, 166.32, 62.3]
b = tf.math.argmin(input = a)
c = tf.keras.backend.eval(b)
}];
let arguments = (
ins TFL_TensorOf<[F32, I32, I8, UI8, QI8, QUI8]>:$input,
TFL_I32OrI64Tensor:$dim
);
let results = (outs
TFL_I32OrI64Tensor:$output
);
let hasOptions = 1;
DerivedTFLiteTypeAttr output_type = DerivedTFLiteTypeAttr<[{
return getResult().getType().cast<TensorType>().getElementType().
cast<IntegerType>().getWidth() > 32 ? tflite::TensorType_INT64 :
tflite::TensorType_INT32;
}], [{
TypeAttr::get(getResult().getType().cast<TensorType>().getElementType())
}]>;
}
def TFL_CeilOp: TFL_Op<"ceil", [
NoSideEffect,
SameOperandsAndResultShape,
SameOperandsAndResultType]> {
let summary = "Ceil operator";
let description = [{
Returns element-wise ceil value of the input.
}];
let arguments = (ins TFL_FpTensor:$x);
let results = (outs TFL_FpTensor:$y);
}
def TFL_ConcatenationOp : TFL_Op<"concatenation",
[
NoSideEffect,
PredOpTrait<"values and output must have same element type",
TFL_TCresVTEtIsSameAsOp<0, 0>>,
SameOperandsAndResultsScale,
TFL_GpuTargetOp
]> {
let summary = "Concatenation operator";
let description = [{
Concatenates tensors along one dimension
}];
let arguments = (
ins TFL_VariadicTensorOf<
[F32, I64, I32, I16, I8, QI8, QUI8, UI8]>:$values,
I32Attr:$axis,
TFL_AFAttr:$fused_activation_function
);
let results = (outs
TFL_TensorOf<
[F32, I64, I32, I16, I8, QI8, QUI8, UI8]>:$output
);
let hasOptions = 1;
let hasFolder = 1;
let verifier = [{ return Verify(*this); }];
}
def TFL_ConstOp : Op<TFL_Dialect, "pseudo_const", [ConstantLike, NoSideEffect,
FirstAttrDerivedResultType]> {
let summary = "Constant pseudo op.";
let description = [{
Represents a constant value in TensorFlow Lite dialect. This is not an
actual operation and it will be lowered to buffer instead.
The op is allowed to have all the same type of attributes as tf.Const does
(e.g., opaque TF attributes are allowed).
}];
let arguments = (ins ElementsAttr:$value);
let results = (outs AnyTensor:$output);
let hasFolder = 1;
let builders = [OpBuilder<
"OpBuilder &, OperationState &state, Attribute value",
[{
state.addAttribute("value", value);
state.addTypes(value.getType());
}]>
];
}
// Attributes used for encoding sparse tensors.
// Please find detailed explanation of these parameters in the TFLite schema.
def TFL_DT_Dense : StrEnumAttrCase<"DENSE", 0>;
def TFL_DT_SparseCSR : StrEnumAttrCase<"SPARSE_CSR", 1>;
def TFL_DimensionTypeAttr : StrEnumAttr<
"DimensionType", "dimension type", [TFL_DT_Dense, TFL_DT_SparseCSR]>;
def DimensionMetadataAttr : StructAttr<"DimensionMetadataAttr", TFL_Dialect, [
StructFieldAttr<"format", TFL_DimensionTypeAttr>,
StructFieldAttr<"dense_size", I32Attr>,
StructFieldAttr<"segments", I32ArrayAttr>,
StructFieldAttr<"indices", I32ArrayAttr>] > {
let description = "Dimension metadata.";
}
def DimensionMetadataArrayAttr : TypedArrayAttrBase<DimensionMetadataAttr,
"Array of DimensionMetadata">{}
def SparsityParameterAttr : StructAttr<"SparsityParameterAttr", TFL_Dialect, [
StructFieldAttr<"traversal_order", I32ArrayAttr>,
StructFieldAttr<"block_map", I32ArrayAttr>,
StructFieldAttr<"dim_metadata", DimensionMetadataArrayAttr>]> {
let description = "Sparsity parameter.";
let storageType = [{ TFL::SparsityParameterAttr }];
}
def TFL_SparseConstOp : Op<TFL_Dialect, "pseudo_sparse_const", [
NoSideEffect,
FirstAttrDerivedResultType]> {
let summary = "Sparse constant pseudo op.";
let description = [{
Represents a sparse constant value in TensorFlow Lite dialect. This is not
an actual operation and it will be lowered to buffer instead.
}];
let arguments = (ins ElementsAttr:$value,
SparsityParameterAttr:$s_param,
ElementsAttr:$compressed_data);
let results = (outs AnyTensor:$output);
let builders = [OpBuilder<
"OpBuilder &, OperationState &state, Attribute value, "
"SparsityParameterAttr s_param, Attribute compressed_data",
[{
state.addTypes(value.getType());
state.addAttribute("value", value);
state.addAttribute("s_param", s_param);
state.addAttribute("compressed_data", compressed_data);
}]>
];
}
def TFL_ExternalConstOp : Op<TFL_Dialect, "external_const", [NoSideEffect]> {
let summary = "External const op.";
let description = [{
External const op holds a `buffer_index` which points to a constant
in the flatbuffer.
}];
let arguments = (ins I32Attr:$buffer_index);
let results = (outs AnyTensor:$output);
}
def TFL_Conv2DOp : TFL_ConvOp<"conv_2d", "Convolution", 0> {
let extraClassDeclaration = [{
// ChannelDimIndexInterface:
int GetChannelDimIndex() { return 0; }
// SparseOpInterface:
std::vector<int> GetSparseOperands() { return {1}; }
std::vector<std::vector<int>> GetFloatBlockSize() { return {}; }
std::vector<std::vector<int>> GetQuantizedBlockSize() { return {}; }
}];
}
def TFL_CosOp: TFL_Op<"cos", [
NoSideEffect,
SameOperandsAndResultShape,
SameOperandsAndResultType,
NoQuantizableResult,
TFL_GpuTargetOp]> {
let summary = "Cosine operator";
let description = [{
Computes element-wise Cosine of input
}];
let arguments = (ins TFL_FpTensor:$x);
let results = (outs TFL_FpTensor:$y);
let hasFolder = 1;
}
def TFL_DepthwiseConv2DOp :
TFL_ConvOp<"depthwise_conv_2d", "Depthwise-separable convolution", 3> {
let arguments = (
ins TFL_TensorOf<[F32, QI8, QUI8, QI16]>:$input,
TFL_TensorOf<[F32, QI8, QUI8]>:$filter,
TFL_TensorOfOrNone<[F32, I32, I64]>:$bias,
I32Attr:$dilation_h_factor,
I32Attr:$dilation_w_factor,
TFL_AFAttr:$fused_activation_function,
TFL_PaddingAttr:$padding,
I32Attr:$stride_h,
I32Attr:$stride_w,
I32Attr:$depth_multiplier
);
let extraClassDeclaration = [{
// ChannelDimIndexInterface:
int GetChannelDimIndex() { return 3; }
// SparseOpInterface:
std::vector<int> GetSparseOperands() { return {1}; }
std::vector<std::vector<int>> GetFloatBlockSize() { return {}; }
std::vector<std::vector<int>> GetQuantizedBlockSize() { return {}; }
}];
}
def TFL_FCWO_Default : StrEnumAttrCase<"DEFAULT">;
def TFL_FCWO_Shuffled4x16i8 : StrEnumAttrCase<"SHUFFLED4x16INT8">;
def TFL_FullyConnectedOptionsWeightFormatAttr :
StrEnumAttr<"FullyConnectedOptionsWeightsFormat",
"fully connected options weights format", [
TFL_FCWO_Default, TFL_FCWO_Shuffled4x16i8
]>;
// TODO(jpienaar): Update post discussion on semantics of FC OP.
def TFL_FullyConnectedOp : TFL_Op<"fully_connected", [
NoSideEffect, AccumulatorUniformScale<2, 0, 1>,
TFL_ChannelDimIndexInterface,
AffineOpCoefficient<-1, 1>,
TFL_SparseOp,
TFL_GpuTargetOp]> {
let summary = "Fully connected op";
let arguments = (ins
TFL_TensorOf<[F32, QI8, QUI8, QI16, QUI16]>:$input,
TFL_TensorOf<[F32, QI8, QUI8, QI16, QUI16]>:$filter,
TFL_TensorOfOrNone<[F32, QI32, QUI32]>:$bias,
TFL_AFAttr:$fused_activation_function,
TFL_FullyConnectedOptionsWeightFormatAttr:$weights_format,
BoolAttr:$keep_num_dims
);
// Depending on the weights format, this op can have one or two outputs.
let results = (outs
TFL_VariadicTensorOf<[F32, QI8, QUI8, QI16, QUI16]>:$output
);
let verifier = [{ return Verify(*this); }];
let hasOptions = 1;
let extraClassDeclaration = [{
// ChannelDimIndexInterface:
int GetChannelDimIndex() { return 0; }
// SparseOpInterface:
std::vector<int> GetSparseOperands() { return {1}; }
std::vector<std::vector<int>> GetFloatBlockSize() { return {{1, 4}}; }
std::vector<std::vector<int>> GetQuantizedBlockSize() { return {{1, 16}}; }
}];
}
def TFL_BatchMatMulOp : TFL_Op<"batch_matmul", [
NoSideEffect,
TFL_OperandHasAtleastRank<0, 2>,
TFL_OperandHasAtleastRank<1, 2>,
SameOperandsAndResultElementType]> {
let summary = "Batch Matrix Multiply Operator";
let description = [{
Performs a batched matrix multiplication on the inputs. Follows the
conventions of TensorFlow BatchMatMulV2, with support for unknown dimensions
in the batch dimensions and broadcasting.
Inputs:
`inputs[0]`: required: input LHS
`inputs[1]`: required: input RHS
`adjoint_lhs`: optional: Transpose LHS (default false)
`adjoint_lhs`: optional: Transpose LHS (default false)
}];
let arguments = (ins
TFL_TensorOf<[F32, QI8]>:$x,
TFL_TensorOf<[F32, QI8]>:$y,
DefaultValuedAttr<BoolAttr, "false">:$adj_x,
DefaultValuedAttr<BoolAttr, "false">:$adj_y
);
let results = (outs
TFL_TensorOf<[F32, QI8]>:$output
);
let hasOptions = 1;
}
def TFL_GatherOp : TFL_Op<"gather", [
NoSideEffect,
SameOperandsAndResultsScale,
TFL_OperandHasAtleastRank<0, 1>,
PredOpTrait<"params and output must have same element type",
TFL_TCresVTEtIsSameAsOp<0, 0>>
]> {
let summary = "Gather operator";
let description = [{
Gather slices from `params` axis `axis` according to `indices`.
}];
let arguments = (ins
TFL_TensorOf<[F32, I1, I8, I32, I64, TFL_Str, UI8, QI8, QUI8]>:$params,
TFL_TensorOf<[I32, I64]>:$indices,
I32Attr:$axis
);
let builders =
[
OpBuilder<"OpBuilder &builder, OperationState &result, "
"Value params, Value indices, IntegerAttr axis",
[{ BuildGatherOp(&builder, result, params, indices, axis); }]>
];
let results = (outs
TFL_TensorOf<[F32, I1, I8, I32, I64, TFL_Str, UI8, QI8, QUI8]>:$output