-
Notifications
You must be signed in to change notification settings - Fork 6k
Expand file tree
/
Copy pathop_gen.py
More file actions
2128 lines (1920 loc) · 85.6 KB
/
op_gen.py
File metadata and controls
2128 lines (1920 loc) · 85.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2023 PaddlePaddle 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.
import argparse
import logging
import os
import pathlib
import sys
import yaml
from decomp_interface_gen_op_list import decomp_interface_declare_gen_op_list
from infer_symbolic_shape_gen import gen_infer_symbolic_shape_str
from op_build_gen import gen_build_func_str, gen_build_func_str_by_invoke
from op_interface_gen import (
gen_exclusive_interface_str,
gen_op_infer_meta_str,
gen_op_vjp_str,
)
from op_kerneltype_gen import gen_kernel_type_for_var_str
from op_member_func_gen import gen_op_get_inputs_outputs_str
from op_verify_gen import gen_verify_func_str
from ops_onednn_extra_parser import parse_extra_args, parse_layout_transform
from parse_kernel_key_gen import gen_parse_kernel_key_str
from vjp_interface_black_list import vjp_interface_black_list
# import from paddle/fluid/primitive/code_gen/gen.py
sys.path.append(
str(pathlib.Path(__file__).resolve().parents[3] / 'primitive/codegen')
)
import gen as vjp_gen
# Note(Galaxy1458) The need_export_symbol_op_list is used
# for some unittests these need to export symbol op compiled with dynamic lib.
need_export_symbol_op_list = ['AbsOp', 'FullOp', 'UniformOp']
# =====================================
# String Template for h file code gen
# =====================================
NAMESPACE_GARD_TEMPLATE = """namespace {namespace} {{
{input}
}} // namespace {namespace}"""
H_FILE_TEMPLATE = """// This file is generated by "paddle/fluid/pir/dialect/op_generator/op_gen.py"
#pragma once
#include <vector>
#include "paddle/pir/core/builder.h"
#include "paddle/pir/core/operation_utils.h"
#include "paddle/fluid/pir/dialect/operator/interface/infer_symbolic_shape.h"
#include "paddle/pir/core/op_base.h"
#include "paddle/pir/core/op_trait.h"
#include "paddle/fluid/pir/dialect/operator/utils/utils.h"
#include "paddle/fluid/pir/dialect/operator/utils/op_yaml_info_util.h"
#include "paddle/fluid/pir/dialect/operator/interface/op_yaml_info.h"
#include "paddle/fluid/pir/dialect/operator/interface/infermeta.h"
#include "paddle/fluid/pir/dialect/operator/interface/vjp.h"
#include "paddle/fluid/pir/dialect/operator/interface/parse_kernel_key.h"
#include "paddle/fluid/pir/dialect/operator/interface/decomp.h"
#include "paddle/fluid/pir/dialect/operator/trait/inplace.h"
#include "paddle/fluid/pir/dialect/operator/trait/onednn.h"
#include "paddle/fluid/pir/dialect/operator/trait/custom_vjp.h"
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/fluid/pir/dialect/operator/ir/manual_op.h"
#include "paddle/fluid/ir_adaptor/translator/utils.h"
{only_pd_op_header_files}
{op_to_multi_kernels_map}
{input}
{declare_type_id}
"""
OP_TO_MULTI_KERNELS_MAP_H = """
extern std::unordered_map<std::string, std::vector<PdOpSig>> op_to_multi_kernels_map;
"""
GET_OP_LIST_TEMPALTE = """{}
"""
DECLARE_OP_TYPE_ID = """
IR_DECLARE_EXPLICIT_TYPE_ID({op_name})
"""
OP_DECLARE_TEMPLATE = """
class {TEST_API} {op_name} : public pir::Op<{op_name}{interfaces}{traits}> {{
public:
using Op::Op;
static const char *name() {{ return "{dialect_op_name}"; }}
{attribute_declare}
static constexpr uint32_t attributes_num = {attribute_num};
static OpInfoTuple GetOpInfo();
static void Build({build_args});
{build_mutable_attr_is_input}
{build_attr_num_over_1}
{build_mutable_attr_is_input_attr_num_over_1}
void VerifySig();
{get_kernel_type_for_var_declare}
{parse_kernel_key_declare}
{infer_symbolic_shape_declare}
{get_inputs_and_outputs}
{exclusive_interface}
}};
"""
op_0_attribute_declare_str = (
"static constexpr const char **attributes_name = nullptr;"
)
op_n_attribute_declare_str = (
"static const char *attributes_name[{attribute_num}];"
)
get_kernel_type_for_var_declare_template = """
static phi::DataType GetKernelTypeForVar(
const std::string& var_name,
const phi::DataType& tensor_dtype,
const phi::DataType& expected_kernel_dtype);
"""
parse_kernel_key_template = """
static std::tuple<phi::DataType, phi::Backend> ParseKernelKey(pir::Operation *op);
"""
infer_symbolic_shape_template = """
bool InferSymbolicShape(pir::ShapeConstraintIRAnalysis* shape_analysis);
"""
# =====================================
# String Template for cc file code gen
# =====================================
CC_FILE_TEMPLATE = """// This file is generated by "paddle/fluid/pir/dialect/op_generator/op_gen.py"
#include "{h_file}"
#include "paddle/fluid/pir/dialect/operator/ir/op_type.h"
#include "paddle/fluid/pir/dialect/operator/ir/op_attribute.h"
#include "paddle/fluid/pir/dialect/operator/ir/ir_tensor.h"
#include "paddle/fluid/pir/dialect/operator/ir/ir_selected_rows.h"
#include "paddle/fluid/pir/dialect/operator/ir/ir_meta_tensor.h"
#include "paddle/pir/core/builtin_attribute.h"
#include "paddle/pir/core/builtin_type.h"
#include "paddle/pir/core/builtin_op.h"
#include "paddle/pir/core/ir_context.h"
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/infermeta/binary.h"
#include "paddle/phi/infermeta/multiary.h"
#include "paddle/phi/infermeta/nullary.h"
#include "paddle/phi/infermeta/unary.h"
#include "paddle/phi/infermeta/ternary.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/fusion.h"
#include "paddle/phi/api/lib/utils/allocator.h"
#include "paddle/fluid/primitive/rule/vjp/vjp.h"
#include "paddle/pir/core/op_base.h"
{input}
{define_type_id}
"""
CC_OP_INFO_FILE_TEMPLATE_PART1 = """#ifdef GET_OP_LIST
#undef GET_OP_LIST
{op_declare}
"""
CC_OP_INFO_FILE_TEMPLATE_WIN_PART1 = """#ifdef GET_OP_LIST1
#undef GET_OP_LIST1
{op_declare_first_part}
#elif defined(GET_OP_LIST2)
#undef GET_OP_LIST2
{op_declare_second_part}
"""
CC_OP_INFO_FILE_TEMPLATE_PART2 = """
#else
// This file is generated by "paddle/fluid/pir/dialect/op_generator/op_gen.py"
#include "{h_file}"
{op_to_multi_kernels_map}
#endif
"""
# =====================================
# String Template for pd_op_vjp.cc file code gen
# =====================================
VJP_CC_FILE_TEMPLATE = """// This file is generated by "paddle/fluid/pir/dialect/op_generator/op_gen.py"
#include "paddle/fluid/pir/dialect/operator/ir/op_attribute.h"
#include "paddle/fluid/pir/dialect/operator/ir/pd_op.h"
#include "paddle/fluid/primitive/rule/vjp/vjp.h"
#include "paddle/fluid/primitive/type/lazy_tensor.h"
#include "paddle/pir/core/builtin_op.h"
#include "paddle/pir/core/op_base.h"
#include "paddle/phi/common/int_array.h"
#include "paddle/fluid/pir/dialect/operator/utils/utils.h"
namespace paddle {{
namespace dialect {{
{input}
}} // namespace dialect
}} // namespace paddle
"""
OP_N_ATTRIBUTE_DEFINED_TEMPLATE = """
const char *{op_name}::attributes_name[{attribute_num}] = {{ {attribute_names} }};
"""
# get op info
OP_INFO_TEMPLATE = """
OpInfoTuple {op_name}::GetOpInfo() {{
std::vector<paddle::dialect::OpInputInfo> inputs = {{ {inputs} }};
std::vector<paddle::dialect::OpAttributeInfo> attributes = {{ {attributes} }};
std::vector<paddle::dialect::OpOutputInfo> outputs = {{ {outputs} }};
paddle::dialect::OpRunTimeInfo run_time_info = paddle::dialect::OpRunTimeInfo("{infer_meta_func}", {{"{infer_meta_param}"}}, "{kernel_func}", {{"{kernel_param}"}}, {{{kernel_key_dtype}}}, {{{kernel_key_backend}}}, {{{inplace}}}, {{{view}}});
return std::make_tuple(inputs, attributes, outputs, run_time_info, "{origin_op_name}");
}}
"""
OP_INFO_ONEDNN_TEMPLATE = """
OpInfoTuple {op_name}::GetOpInfo() {{
std::vector<paddle::dialect::OpInputInfo> inputs = {{ {inputs} }};
std::vector<paddle::dialect::OpAttributeInfo> attributes = {{ {attributes} }};
std::vector<paddle::dialect::OpOutputInfo> outputs = {{ {outputs} }};
paddle::dialect::OpRunTimeInfo run_time_info = paddle::dialect::OpRunTimeInfo("{infer_meta_func}", {{"{infer_meta_param}"}}, "{kernel_func}", {{"{kernel_param}"}}, {{{kernel_key_dtype}}}, {{{kernel_key_backend}}}, {{{inplace}}}, {{{view}}}, {{{extra_args}}}, "{layout_transform_arg}", {{{layout_transform_inputs}}}, {is_onednn_only}, {dynamic_fallback});
return std::make_tuple(inputs, attributes, outputs, run_time_info, "{origin_op_name}");
}}
"""
CONSTRUCT_INPUT_INFO_TEMPLATE = """paddle::dialect::OpInputInfo("{name}", "{typename}", {optional}, {no_need_buffer}, {is_mutable_attribute}, {with_grad_semantic})"""
CONSTRUCT_OUTPUT_INFO_TEMPLATE = """paddle::dialect::OpOutputInfo("{name}", "{typename}", {optional}, {intermediate})"""
CONSTRUCT_ATTRIBUTE_INFO_TEMPLATE = """paddle::dialect::OpAttributeInfo("{name}", "{typename}", "{data_type}")"""
DEFINE_OP_TYPE_ID = """
IR_DEFINE_EXPLICIT_TYPE_ID({op_name})
"""
OP_TO_MULTI_KERNELS_MAPS = """
std::unordered_map<std::string, std::vector<PdOpSig>> op_to_multi_kernels_map = {{
{maps}
}};
"""
scalar_type_maps = {
'int': 'pir::Int32Attribute',
'int64_t': 'pir::Int64Attribute',
'float': 'pir::FloatAttribute',
'dobule': 'pir::DoubleAttribute',
'bool': 'pir::BoolAttribute',
}
PD_MANUAL_OP_LIST = {
'add_n',
'add_n_',
'add_n_with_kernel',
'split_grad',
'expand',
'increment',
'increment_',
}
attr_types_map = {
'IntArray': ['paddle::dialect::IntArrayAttribute', 'IntArray'],
'Scalar': ['paddle::dialect::ScalarAttribute', 'Scalar'],
'Scalar(int)': ['pir::Int32Attribute', 'int'],
'Scalar(int64_t)': ['pir::Int64Attribute', 'int64_t'],
'Scalar(float)': ['pir::FloatAttribute', 'float'],
'Scalar(double)': ['pir::DoubleAttribute', 'double'],
'Scalar[]': [
'pir::ArrayAttribute<paddle::dialect::ScalarAttribute>',
'const std::vector<Scalar>&',
],
'int': ['pir::Int32Attribute', 'int'],
'int32_t': ['pir::Int32Attribute', 'int32_t'],
'int64_t': ['pir::Int64Attribute', 'int64_t'],
'long': ['pir::LongAttribute', 'long'],
'size_t': ['pir::Size_tAttribute', 'size_t'],
'float': ['pir::FloatAttribute', 'float'],
'float[]': [
'pir::ArrayAttribute<pir::FloatAttribute>',
'const std::vector<float>&',
],
'double': ['pir::DoubleAttribute', 'double'],
'bool': ['pir::BoolAttribute', 'bool'],
'bool[]': [
'pir::ArrayAttribute<pir::BoolAttribute>',
'const std::vector<bool>&',
],
'str': ['pir::StrAttribute', 'const std::string&'],
'str[]': [
'pir::ArrayAttribute<pir::StrAttribute>',
'const std::vector<std::string>&',
],
'Place': ['paddle::dialect::PlaceAttribute', 'const Place&'],
'DataLayout': [
'paddle::dialect::DataLayoutAttribute',
'DataLayout',
],
'DataType': ['paddle::dialect::DataTypeAttribute', 'DataType'],
'int64_t[]': [
'pir::ArrayAttribute<pir::Int64Attribute>',
'const std::vector<int64_t>&',
],
'int[]': [
'pir::ArrayAttribute<pir::Int32Attribute>',
'const std::vector<int>&',
],
}
def to_phi_and_fluid_op_name(op_item):
# Templat: - op : phi_name (fluid_name)
names = op_item.split('(')
if len(names) == 1:
phi_fluid_name = names[0].strip()
return phi_fluid_name, phi_fluid_name
else:
phi_name = names[0].strip()
fluid_name = names[1].split(')')[0].strip()
return phi_name, fluid_name
def to_phi_and_fluid_grad_op_name(op_item):
# Templat: sum_grad (reduce_sum_grad), sum_double_grad
rtn = []
all_names = op_item.split(', ')
for name in all_names:
backward_phi_name, backward_fluid_name = to_phi_and_fluid_op_name(name)
rtn.append([backward_phi_name, backward_fluid_name])
return rtn
# =====================================
# Parse Op Compat From Yaml
# =====================================
class OpCompatParser:
def __init__(self, ops_compat_yaml_file):
self.ops_compat_yaml_file = ops_compat_yaml_file
with open(self.ops_compat_yaml_file, "r") as f:
self.ops_compat = yaml.safe_load(f)
def get_compat(self, op_name):
for compat in self.ops_compat:
forward_phi_name, forward_fluid_name = to_phi_and_fluid_op_name(
compat['op']
)
if op_name == forward_phi_name:
return compat
elif 'backward' in compat.keys():
bkw_names = to_phi_and_fluid_grad_op_name(compat['backward'])
for name in bkw_names:
if op_name == name[0]:
return compat
return None
def parse_support_tensor(self, op):
scalar_item = {}
int_array_item = {}
for support_tensor_attr in op['support_tensor']:
for attr in op['attrs']:
if (
attr['typename'] == 'Scalar'
and attr['name'] == support_tensor_attr
):
scalar_item[support_tensor_attr] = {"support_tensor": True}
if (
attr['typename'] == 'IntArray'
and attr['name'] == support_tensor_attr
):
scalar_item[support_tensor_attr] = {"support_tensor": True}
return scalar_item, int_array_item
# =====================================
# Parse Op Information From Yaml
# =====================================
class OpInfoParser:
def __init__(self, op_yaml_item, op_compat_item):
self.op_yaml_item = op_yaml_item
self.op_compat_item = op_compat_item
self.op_phi_name = self.parse_op_phi_name()
self.kernel_map = self.parse_kernel_map()
# parse inputs
self.input_name_list = self.parse_input_name_list()
self.input_type_list = self.parse_input_type_list()
self.input_type_dict = self.parse_input_type_dict()
self.input_optional_list = self.parse_input_optional_list()
self.input_no_need_buffer_list = self.parse_input_no_need_buffer_list()
self.cross_check(
self.input_name_list, self.input_type_list, self.input_optional_list
)
# parse outputs
self.output_name_list = self.parse_output_name_list()
self.output_type_list = self.parse_output_type_list()
self.output_type_dict = self.parse_output_type_dict()
self.output_size_list = self.parse_output_size_list()
self.output_optional_list = self.parse_output_optional_list()
self.output_intermediate_list = self.parse_output_intermediate_list()
self.cross_check(
self.output_name_list,
self.output_type_list,
self.output_optional_list,
)
# parse attributes
self.attr_types_map = attr_types_map
self.attribute_name_list = self.parse_attribute_name_list()
self.attribute_type_list = self.parse_attribute_type_list()
self.attribute_build_arg_type_list = (
self.parse_attribute_build_arg_type_list()
)
self.attribute_gen_arg_type_list = (
self.parse_attribute_gen_arg_type_list()
)
self.attribute_data_type_list = self.parse_attribute_data_type_list()
self.attribute_default_value_list = (
self.parse_attribute_default_value_list()
)
self.cross_check(self.attribute_name_list, self.attribute_type_list)
# parse mutable attributes (as inputs)
(
self.mutable_attribute_name_list,
self.mutable_attribute_type_list,
) = self.parse_mutable_attribute()
(
self.non_mutable_attribute_name_list,
self.non_mutable_attribute_type_list,
self.non_mutable_attribute_data_type_list,
self.non_mutable_attribute_build_arg_type_list,
self.non_mutable_attribute_default_value_list,
) = self.parse_non_mutable_attribute()
# parse infermeta && kernel
self.infer_meta_map = self.parse_infer_meta_map()
self.invoke_map = self.parse_invoke_map()
if 'infer_meta' in self.op_yaml_item:
self.infer_meta_func = self.op_yaml_item['infer_meta']["func"]
else:
self.infer_meta_func = None
if 'infer_shaped_type_op_interface' in self.op_yaml_item:
self.infer_shaped_type_op_interface_func = self.op_yaml_item[
'infer_shaped_type_op_interface'
]["func"]
else:
self.infer_shaped_type_op_interface_func = None
# parse backward name
self.backward_name = self.parse_backward_name()
# parse inplace && view
self.inplace_map = self.parse_op_inplace_info()
self.view_map = self.parse_op_view_info()
# parse data_transform
self.data_transform_map = self.parse_data_transform_info()
# parse has_custom_verify
self.custom_verify = self.parse_custom_verify()
# parse forward input name list and attribute name list
self.forward_input_name_list = self.parse_forward_input_name()
# parse forward output name list
self.forward_output_name_list = self.parse_forward_output_name()
# parse traits list
self.traits_list = self.parse_op_traits()
# parse interfaces list
self.interfaces_list = self.parse_op_interfaces()
# OneDNN info
if "extra_args" in self.op_yaml_item:
self.onednn_extra_args = self.op_yaml_item["extra_args"]
self.onednn_layout_transform = self.op_yaml_item["layout_transform"]
self.is_onednn_only = self.op_yaml_item["is_onednn_only"]
self.dynamic_fallback = self.op_yaml_item["dynamic_fallback"]
else:
self.onednn_extra_args = []
self.onednn_layout_transform = None
self.is_onednn_only = False
self.dynamic_fallback = False
def parse_op_traits(self):
if 'traits' in self.op_yaml_item:
return self.op_yaml_item['traits']
else:
return []
def parse_op_interfaces(self):
if 'interfaces' in self.op_yaml_item:
return self.op_yaml_item['interfaces']
else:
return []
def parse_forward_input_name(self):
if 'forward' in self.op_yaml_item:
forward_input_name_list = []
forward_map = self.op_yaml_item['forward']
if forward_map is not None:
inputs = forward_map['inputs']
for input in inputs:
forward_input_name_list.append(input['name'])
return forward_input_name_list
else:
return None
else:
return None
def parse_forward_output_name(self):
if 'forward' in self.op_yaml_item:
forward_output_name_list = []
forward_map = self.op_yaml_item['forward']
if forward_map is not None:
outputs = forward_map['outputs']
for output in outputs:
forward_output_name_list.append(output['name'])
return forward_output_name_list
else:
return None
else:
return None
def cross_check(self, name_list, type_list, optional_list=None):
assert len(name_list) == len(
type_list
), "name list size != type list size."
if optional_list is not None:
assert len(name_list) == len(
optional_list
), "type list size != optional list size."
def parse_custom_verify(self):
if 'custom_verify' in self.op_yaml_item:
return self.op_yaml_item['custom_verify']
return False
def parse_op_phi_name(self):
if (self.parse_op_inplace_info() is None) and (
self.parse_op_view_info() is None
):
return [self.op_yaml_item['name']]
else:
if self.op_yaml_item['name'][-1] == "_":
return [self.op_yaml_item['name']]
else:
return [
self.op_yaml_item['name'],
self.op_yaml_item['name'] + "_",
]
def parse_op_inplace_info(self):
if 'inplace' in self.op_yaml_item:
return self.op_yaml_item['inplace']
return None
def parse_op_view_info(self):
if 'view' in self.op_yaml_item:
return self.op_yaml_item['view']
return None
def is_mutable_attribute(self, attr_dict):
if (
'support_tensor' in attr_dict
and attr_dict['support_tensor'] is True
):
return True
elif 'tensor_name' in attr_dict or 'tensors_name' in attr_dict:
return True
else:
return False
def parse_mutable_attribute(self):
"""
{'axis': 'paddle::dialect::ScalarAttribute', 'rotl': 'paddle::dialect::IntArrayAttribute'}
"""
mutable_attribute_name_list = []
mutable_attribute_type_list = []
# scalar
if (self.op_compat_item is not None) and (
'scalar' in self.op_compat_item
):
for scalar_attr in self.op_compat_item['scalar'].keys():
if not self.is_mutable_attribute(
self.op_compat_item['scalar'][scalar_attr]
):
continue
if 'data_type' in self.op_compat_item['scalar'][scalar_attr]:
if (
scalar_attr == "depth"
and self.op_phi_name[0] == "one_hot"
):
mutable_attribute_name_list.append("num_classes")
else:
mutable_attribute_name_list.append(scalar_attr)
data_type = self.op_compat_item['scalar'][scalar_attr][
'data_type'
]
# patch for isclose and allclose
if (self.op_compat_item['op'] == "isclose") or (
self.op_compat_item['op'] == "allclose"
):
data_type = "double"
mutable_attribute_type_list.append(
[
"paddle::dialect::ScalarAttribute",
data_type,
]
)
# See eye in op_compat.yaml
else:
mutable_attribute_name_list.append(scalar_attr)
mutable_attribute_type_list.append(
[
"paddle::dialect::ScalarAttribute",
self.attribute_data_type_list[
self.attribute_name_list.index(scalar_attr)
],
]
)
# int_array
if (self.op_compat_item is not None) and (
'int_array' in self.op_compat_item
):
for int_array_attr in self.op_compat_item['int_array']:
if not self.is_mutable_attribute(
self.op_compat_item['int_array'][int_array_attr]
):
continue
mutable_attribute_name_list.append(int_array_attr)
mutable_attribute_type_list.append(
[
"paddle::dialect::IntArrayAttribute",
self.op_compat_item['int_array'][int_array_attr][
'data_type'
],
]
)
sorted_mutable_attribute_name_list = []
sorted_mutable_attribute_type_list = []
for attr_name in self.attribute_name_list:
if attr_name in mutable_attribute_name_list:
sorted_mutable_attribute_name_list.append(attr_name)
sorted_mutable_attribute_type_list.append(
mutable_attribute_type_list[
mutable_attribute_name_list.index(attr_name)
]
)
return (
sorted_mutable_attribute_name_list,
sorted_mutable_attribute_type_list,
)
def parse_non_mutable_attribute(self):
op_non_mutable_attribute_name_list = []
op_non_mutable_attribute_type_list = []
op_non_mutable_attribute_data_type_list = []
op_non_mutable_attribute_build_arg_type_list = []
op_non_mutable_attribute_default_value_list = []
for idx in range(len(self.attribute_name_list)):
if (
self.attribute_name_list[idx]
not in self.mutable_attribute_name_list
):
op_non_mutable_attribute_name_list.append(
self.attribute_name_list[idx]
)
op_non_mutable_attribute_type_list.append(
self.attribute_type_list[idx]
)
op_non_mutable_attribute_data_type_list.append(
self.attribute_data_type_list[idx]
)
op_non_mutable_attribute_build_arg_type_list.append(
self.attribute_build_arg_type_list[idx]
)
op_non_mutable_attribute_default_value_list.append(
self.attribute_default_value_list[idx]
)
return (
op_non_mutable_attribute_name_list,
op_non_mutable_attribute_type_list,
op_non_mutable_attribute_data_type_list,
op_non_mutable_attribute_build_arg_type_list,
op_non_mutable_attribute_default_value_list,
)
def parse_input_name_list(self):
name_list = []
for input_info in self.op_yaml_item['inputs']:
name_list.append(input_info['name'])
return name_list
def parse_input_type_list(self):
input_types_map = {
'Tensor': 'paddle::dialect::DenseTensorType',
'Tensor[]': 'pir::VectorType<paddle::dialect::DenseTensorType>',
}
type_list = []
for input_info in self.op_yaml_item['inputs']:
assert (
input_info['typename'] in input_types_map
), f"{self.op_phi_name} : Input type error: the input type only support Tensor and Tensor[], but now is {input_info['typename']}."
type_list.append(input_types_map[input_info['typename']])
return type_list
def parse_input_type_dict(self):
type_dict = {}
if (
self.kernel_map is None
or self.kernel_map['dispatch'][self.kernel_map['func'][0]] is None
):
input_types_map = {
'Tensor': 'paddle::dialect::DenseTensorType',
'Tensor[]': 'pir::VectorType<paddle::dialect::DenseTensorType>',
}
type_list = []
for input_info in self.op_yaml_item['inputs']:
assert (
input_info['typename'] in input_types_map
), f"{self.op_phi_name} : Input type error: the input type only support Tensor and Tensor[], but now is {input_info['typename']}."
type_list.append(input_types_map[input_info['typename']])
if self.kernel_map is None:
type_dict['default'] = type_list
else:
type_dict[self.kernel_map['func'][0]] = type_list
else:
input_types_map = {
'dense': 'paddle::dialect::DenseTensorType',
'selected_rows': 'paddle::dialect::SelectedRowsType',
}
for kernel_func_name in self.kernel_map['func']:
inputs = self.kernel_map['dispatch'][kernel_func_name][0]
type_list = []
for input_info in inputs:
assert (
input_info in input_types_map
), f"{self.op_phi_name} : Input type error: the input type only support dense and selected_rows, but now is {input_info}."
type_list.append(input_types_map[input_info])
type_dict[kernel_func_name] = type_list
return type_dict
def parse_input_optional_list(self):
optional_list = []
for input_info in self.op_yaml_item['inputs']:
if input_info['optional']:
optional_list.append("true")
else:
optional_list.append("false")
return optional_list
def parse_input_no_need_buffer_list(self):
no_need_buffer_list = []
for input_info in self.op_yaml_item['inputs']:
if input_info['no_need_buffer']:
no_need_buffer_list.append("true")
else:
no_need_buffer_list.append("false")
return no_need_buffer_list
def parse_output_name_list(self):
name_list = []
for output_info in self.op_yaml_item['outputs']:
name_list.append(output_info['name'])
return name_list
def parse_output_type_list(self):
output_type_map = {
'Tensor': 'paddle::dialect::DenseTensorType',
'Tensor[]': 'pir::VectorType<paddle::dialect::DenseTensorType>',
'SelectedRows': 'paddle::dialect::SelectedRowsType',
}
type_list = []
for output_info in self.op_yaml_item['outputs']:
assert (
output_info['typename'] in output_type_map
), f"{self.op_phi_name} : Output type error: the output type only support Tensor and Tensor[], but now is {output_info['typename']}."
type_list.append(output_type_map[output_info['typename']])
return type_list
def parse_output_type_dict(self):
type_dict = {}
if (
self.kernel_map is None
or self.kernel_map['dispatch'][self.kernel_map['func'][0]] is None
):
output_type_map = {
'Tensor': 'paddle::dialect::DenseTensorType',
'Tensor[]': 'pir::VectorType<paddle::dialect::DenseTensorType>',
'SelectedRows': 'paddle::dialect::SelectedRowsType',
}
type_list = []
for output_info in self.op_yaml_item['outputs']:
assert (
output_info['typename'] in output_type_map
), f"{self.op_phi_name} : Output type error: the output type only support Tensor and Tensor[], but now is {output_info['typename']}."
type_list.append(output_type_map[output_info['typename']])
if self.kernel_map is None:
type_dict['default'] = type_list
else:
type_dict[self.kernel_map['func'][0]] = type_list
else:
output_type_map = {
'dense': 'paddle::dialect::DenseTensorType',
'selected_rows': 'paddle::dialect::SelectedRowsType',
}
for kernel_func_name in self.kernel_map['func']:
outputs = self.kernel_map['dispatch'][kernel_func_name][1]
type_list = []
for output_info in outputs:
assert (
output_info in output_type_map
), f"{self.op_phi_name} : Input type error: the input type only support dense and selected_rows, but now is {output_info}."
type_list.append(output_type_map[output_info])
type_dict[kernel_func_name] = type_list
return type_dict
def parse_output_size_list(self):
size_list = []
for output_info in self.op_yaml_item['outputs']:
if 'size' in output_info:
size_list.append(output_info['size'])
else:
size_list.append(None)
return size_list
def parse_output_optional_list(self):
optional_list = []
for output_info in self.op_yaml_item['outputs']:
if 'optional' in output_info or 'intermediate' in output_info:
if output_info['optional'] or output_info['intermediate']:
optional_list.append("true")
else:
optional_list.append("false")
else:
optional_list.append("false")
return optional_list
def parse_output_intermediate_list(self):
intermediate_list = []
for output_info in self.op_yaml_item['outputs']:
if 'intermediate' in output_info:
if output_info['intermediate']:
intermediate_list.append("true")
else:
intermediate_list.append("false")
else:
intermediate_list.append("false")
return intermediate_list
def parse_attribute_name_list(self):
name_list = []
for attribute_info in self.op_yaml_item['attrs']:
name_list.append(attribute_info['name'])
return name_list
def parse_attribute_build_arg_type_list(self):
type_list = []
for attribute_info in self.op_yaml_item['attrs']:
assert (
attribute_info['typename'] in self.attr_types_map
), f"{self.op_phi_name} : Attr type error."
# Scalar & IntArray has data_type
temp_type = self.attr_types_map[attribute_info['typename']][1]
if 'Scalar' in temp_type:
if 'data_type' in attribute_info:
temp_type = attribute_info['data_type']
op_name = self.op_yaml_item['name']
attr_name = attribute_info['name']
if (
op_name not in ["isclose", "allclose"]
and self.op_compat_item is not None
and 'scalar' in self.op_compat_item.keys()
and attr_name in self.op_compat_item['scalar'].keys()
and 'data_type'
in self.op_compat_item['scalar'][attr_name].keys()
):
temp_type = self.op_compat_item['scalar'][attr_name][
'data_type'
]
if 'IntArray' in temp_type:
if 'data_type' in attribute_info:
temp_type = "const " + attribute_info['data_type'] + "&"
type_list.append(self.get_phi_dtype_name(temp_type))
return type_list
def parse_attribute_gen_arg_type_list(self):
type_list = []
for attribute_info in self.op_yaml_item['attrs']:
assert (
attribute_info['typename'] in self.attr_types_map
), f"{self.op_phi_name} : Attr type error."
temp_type = self.attr_types_map[attribute_info['typename']][1]
type_list.append(self.get_phi_dtype_name(temp_type))
return type_list
def parse_attribute_type_list(self):
type_list = []
for attribute_info in self.op_yaml_item['attrs']:
assert (
attribute_info['typename'] in self.attr_types_map
), f"{self.op_phi_name} : Attr type error."
type_list.append(self.attr_types_map[attribute_info['typename']][0])
return type_list
def parse_attribute_data_type_list(self):
data_type_list = []
for attribute_info in self.op_yaml_item['attrs']:
if 'data_type' in attribute_info:
data_type_list.append(attribute_info['data_type'])
else:
data_type_list.append("")
return data_type_list
def parse_attribute_default_value_list(self):
default_value_list = []
for attribute_info in self.op_yaml_item['attrs']:
if 'default_value' in attribute_info:
default_value = attribute_info['default_value']
default_value_list.append(
self.get_phi_dtype_name(default_value)
)
else:
default_value_list.append(None)
return default_value_list
def parse_infer_meta_map(self):
if 'infer_meta' in self.op_yaml_item:
return self.op_yaml_item['infer_meta']
else:
return None
def parse_kernel_map(self):
if 'kernel' in self.op_yaml_item:
return self.op_yaml_item['kernel']
else:
return None
def parse_invoke_map(self):
if 'invoke' in self.op_yaml_item:
return self.op_yaml_item['invoke']
else:
return None
def parse_data_transform_info(self):
if (
'data_transform' in self.op_yaml_item
and self.op_yaml_item['data_transform']
):
data_trans_item = self.op_yaml_item['data_transform']
return data_trans_item
return None
def parse_backward_name(self):
if 'backward' in self.op_yaml_item:
return self.op_yaml_item['backward']
else:
return None
def get_phi_dtype_name(self, name):
name = name.replace('Scalar', 'phi::Scalar')
name = name.replace('IntArray', 'phi::IntArray')
name = name.replace('DataLayout', 'phi::DataLayout')
name = name.replace('DataType', 'phi::DataType')
if name.startswith(
(
"Place",
"CPUPlace",
"GPUPlace",
"GPUPinnedPlace",