op_gen.py 52.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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
16
import logging
17 18 19
import os

import yaml
20
from op_build_gen import gen_build_func_str
21 22 23
from op_interface_gen import (
    gen_exclusive_interface_str,
    gen_op_infer_meta_str,
C
Chen Zhiyang 已提交
24
    gen_op_vjp_str,
25
)
26
from op_member_func_gen import gen_op_get_inputs_outputs_str
27
from op_verify_gen import gen_verify_func_str
28 29 30 31
from vjp_interface_gen_op_list import (
    vjp_interface_declare_gen_op_list,
    vjp_interface_implementation_gen_op_list,
)
32 33 34 35 36 37 38 39 40 41 42 43

# =====================================
# String Template for h file code gen
# =====================================
NAMESPACE_GARD_TEMPLATE = """namespace {namespace} {{
{input}
}} // namespace {namespace}"""

H_FILE_TEMPLATE = """#ifdef GET_OP_LIST
#undef GET_OP_LIST
{op_declare}
#else
44
// This file is generated by "paddle/fluid/ir/dialect/op_generator/op_gen.py"
45

46 47
#include <vector>

48 49
#include "paddle/ir/core/builder.h"
#include "paddle/ir/core/operation_utils.h"
50
#include "paddle/ir/core/op_base.h"
51 52 53 54 55 56
#include "paddle/fluid/ir/dialect/paddle_dialect/utils/utils.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/utils/op_yaml_info_util.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/interface/op_yaml_info.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/interface/infermeta.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/interface/vjp.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/trait/inplace.h"
H
hong 已提交
57 58
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/phi/core/infermeta_utils.h"
59
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_manual_op.h"
H
hong 已提交
60

61
{input}
62 63

{declare_type_id}
64 65 66 67 68 69
#endif
"""

GET_OP_LIST_TEMPALTE = """{}
"""

70 71 72 73
DECLARE_OP_TYPE_ID = """
IR_DECLARE_EXPLICIT_TYPE_ID({op_name})
"""

74 75 76 77 78 79 80
OP_DECLARE_TEMPLATE = """
class {op_name} : public ir::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};
81
  static OpInfoTuple GetOpInfo();
82
  static void Build({build_args});
83
  {build_mutable_attr_is_input}
84
  {build_attr_num_over_1}
85
  void Verify();
86
{get_inputs_and_outputs}
H
hong 已提交
87
{exclusive_interface}
88 89 90 91 92 93 94 95 96 97 98 99
}};
"""
op_0_attribute_declare_str = (
    "static constexpr const char **attributes_name = nullptr;"
)
op_n_attribute_declare_str = (
    "static const char *attributes_name[{attribute_num}];"
)

# =====================================
# String Template for cc file code gen
# =====================================
100
CC_FILE_TEMPLATE = """// This file is generated by "paddle/fluid/ir/dialect/op_generator/op_gen.py"
101
#include "{h_file}"
102 103
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_type.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_attribute.h"
Z
zhangbo9674 已提交
104
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_meta_tensor.h"
105 106
#include "paddle/ir/core/builtin_attribute.h"
#include "paddle/ir/core/builtin_type.h"
107
#include "paddle/ir/core/builtin_op.h"
108
#include "paddle/ir/core/ir_context.h"
109
#include "paddle/phi/core/enforce.h"
110 111 112 113 114 115 116
#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"
Z
zhangbo9674 已提交
117
#include "paddle/phi/infermeta/fusion.h"
118
#include "paddle/phi/api/lib/utils/allocator.h"
119 120
#include "paddle/fluid/primitive/rule/vjp/vjp.h"
#include "paddle/ir/core/op_base.h"
121

122
{input}
123 124

{define_type_id}
125
"""
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
# =====================================
# String Template for pd_op_vjp.cc file code gen
# =====================================
VJP_CC_FILE_TEMPLATE = """// This file is generated by "paddle/fluid/ir/dialect/op_generator/op_gen.py"
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_attribute.h"
#include "paddle/fluid/ir/dialect/paddle_dialect/ir/pd_op.h"
#include "paddle/fluid/primitive/rule/vjp/vjp.h"
#include "paddle/fluid/primitive/type/lazy_tensor.h"
#include "paddle/ir/core/builtin_op.h"
#include "paddle/ir/core/op_base.h"
#include "paddle/phi/common/int_array.h"

namespace paddle {{
namespace dialect {{
{input}
}}  // namespace dialect
}}  // namespace paddle
"""
144 145 146 147 148

OP_N_ATTRIBUTE_DEFINED_TEMPLATE = """
const char *{op_name}::attributes_name[{attribute_num}] = {{ {attribute_names} }};
"""

149
# get op info
150 151
OP_INFO_TEMPLATE = """
OpInfoTuple {op_name}::GetOpInfo() {{
152 153 154
  std::vector<paddle::dialect::OpInputInfo> inputs = {{ {inputs} }};
  std::vector<paddle::dialect::OpAttributeInfo> attributes = {{ {attributes} }};
  std::vector<paddle::dialect::OpOutputInfo> outputs = {{ {outputs} }};
155
  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}}});
156
  return std::make_tuple(inputs, attributes, outputs, run_time_info, "{origin_op_name}");
157 158
}}
"""
159
CONSTRUCT_INPUT_INFO_TEMPLATE = """paddle::dialect::OpInputInfo("{name}", "{typename}", {optional}, {no_need_buffer}, {is_mutable_attribute}, {with_grad_semantic})"""
160 161
CONSTRUCT_OUTPUT_INFO_TEMPLATE = """paddle::dialect::OpOutputInfo("{name}", "{typename}", {optional}, {intermediate})"""
CONSTRUCT_ATTRIBUTE_INFO_TEMPLATE = """paddle::dialect::OpAttributeInfo("{name}", "{typename}", "{data_type}")"""
162

163

164 165 166 167
DEFINE_OP_TYPE_ID = """
IR_DEFINE_EXPLICIT_TYPE_ID({op_name})
"""

168 169 170 171 172 173 174 175
scalar_type_maps = {
    'int': 'ir::Int32Attribute',
    'int64_t': 'ir::Int64Attribute',
    'float': 'ir::FloatAttribute',
    'dobule': 'ir::DoubleAttribute',
    'bool': 'ir::BoolAttribute',
}

176
_NO_NEED_GEN_OPS = {'add_n', 'add_n_', 'add_n_with_kernel', 'split_grad'}
177

178

179 180 181 182 183 184 185 186 187 188 189 190
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


191 192 193 194 195 196 197 198
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
199 200


201
# =====================================
202 203 204 205 206 207 208 209 210 211
# 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:
212 213 214 215
            forward_phi_name, forward_fluid_name = to_phi_and_fluid_op_name(
                compat['op']
            )
            if op_name == forward_phi_name:
216
                return compat
217 218 219 220 221
            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
222 223 224 225 226
        return None


# =====================================
# Parse Op Information From Yaml
227 228
# =====================================
class OpInfoParser:
229
    def __init__(self, op_yaml_item, op_compat_item):
230
        self.op_yaml_item = op_yaml_item
231
        self.op_compat_item = op_compat_item
232
        self.op_phi_name = self.parse_op_phi_name()
233
        # parse inputs
234 235 236
        self.input_name_list = self.parse_input_name_list()
        self.input_type_list = self.parse_input_type_list()
        self.input_optional_list = self.parse_input_optional_list()
237
        self.input_no_need_buffer_list = self.parse_input_no_need_buffer_list()
238 239 240
        self.cross_check(
            self.input_name_list, self.input_type_list, self.input_optional_list
        )
241

242
        # parse outputs
243 244
        self.output_name_list = self.parse_output_name_list()
        self.output_type_list = self.parse_output_type_list()
245
        self.output_size_list = self.parse_output_size_list()
246
        self.output_optional_list = self.parse_output_optional_list()
247
        self.output_intermediate_list = self.parse_output_intermediate_list()
248 249 250 251 252
        self.cross_check(
            self.output_name_list,
            self.output_type_list,
            self.output_optional_list,
        )
253

254
        # parse attributes
255 256 257
        self.attr_types_map = {
            'IntArray': ['paddle::dialect::IntArrayAttribute', 'IntArray'],
            'Scalar': ['paddle::dialect::ScalarAttribute', 'Scalar'],
Z
zhangbo9674 已提交
258 259
            'Scalar(int)': ['ir::Int32Attribute', 'int'],
            'Scalar(int64_t)': ['ir::Int64Attribute', 'int64_t'],
260 261
            'Scalar(float)': ['ir::FloatAttribute', 'float'],
            'Scalar(dobule)': ['ir::DoubleAttribute', 'dobule'],
262 263
            'Scalar[]': [
                'ir::ArrayAttribute<paddle::dialect::ScalarAttribute>',
264
                'const std::vector<Scalar>&',
265
            ],
Z
zhangbo9674 已提交
266 267 268
            'int': ['ir::Int32Attribute', 'int'],
            'int32_t': ['ir::Int32Attribute', 'int32_t'],
            'int64_t': ['ir::Int64Attribute', 'int64_t'],
269 270 271 272 273
            'long': ['ir::LongAttribute', 'long'],
            'size_t': ['ir::Size_tAttribute', 'size_t'],
            'float': ['ir::FloatAttribute', 'float'],
            'float[]': [
                'ir::ArrayAttribute<ir::FloatAttribute>',
274
                'const std::vector<float>&',
275 276 277 278 279
            ],
            'double': ['ir::DoubleAttribute', 'double'],
            'bool': ['ir::BoolAttribute', 'bool'],
            'bool[]': [
                'ir::ArrayAttribute<ir::BoolAttribute>',
W
WangZhen 已提交
280
                'const std::vector<bool>&',
281
            ],
Y
YuanRisheng 已提交
282
            'str': ['ir::StrAttribute', 'const std::string&'],
283 284
            'str[]': [
                'ir::ArrayAttribute<ir::StrAttribute>',
285
                'const std::vector<std::string>&',
286
            ],
Y
YuanRisheng 已提交
287
            'Place': ['paddle::dialect::PlaceAttribute', 'const Place&'],
288 289 290 291 292 293
            'DataLayout': [
                'paddle::dialect::DataLayoutAttribute',
                'DataLayout',
            ],
            'DataType': ['paddle::dialect::DataTypeAttribute', 'DataType'],
            'int64_t[]': [
Z
zhangbo9674 已提交
294
                'ir::ArrayAttribute<ir::Int64Attribute>',
295
                'const std::vector<int64_t>&',
296 297
            ],
            'int[]': [
Z
zhangbo9674 已提交
298
                'ir::ArrayAttribute<ir::Int32Attribute>',
299
                'const std::vector<int>&',
300 301
            ],
        }
302 303
        self.attribute_name_list = self.parse_attribute_name_list()
        self.attribute_type_list = self.parse_attribute_type_list()
304 305 306
        self.attribute_build_arg_type_list = (
            self.parse_attribute_build_arg_type_list()
        )
C
Chen Zhiyang 已提交
307 308 309
        self.attribute_gen_arg_type_list = (
            self.parse_attribute_gen_arg_type_list()
        )
310
        self.attribute_data_type_list = self.parse_attribute_data_type_list()
311 312 313
        self.attribute_default_value_list = (
            self.parse_attribute_default_value_list()
        )
314 315
        self.cross_check(self.attribute_name_list, self.attribute_type_list)

316 317 318 319 320 321
        # parse mutable attributes (as inputs)
        (
            self.mutable_attribute_name_list,
            self.mutable_attribute_type_list,
        ) = self.parse_mutable_attribute()

322 323 324 325 326 327 328 329
        (
            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_nutable_attribute()

330 331 332
        # parse infermeta && kernel
        self.infer_meta_map = self.parse_infer_meta_map()
        self.kernel_map = self.parse_kernel_map()
H
hong 已提交
333
        if 'infer_meta' in self.op_yaml_item:
334
            self.infer_meta_func = self.op_yaml_item['infer_meta']["func"]
H
hong 已提交
335
        else:
336
            self.infer_meta_func = None
H
hong 已提交
337

338 339 340
        # parse backward name
        self.backward_name = self.parse_backward_name()

341 342 343 344
        # parse inplace && view
        self.inplace_map = self.parse_op_inplace_info()
        self.view_map = self.parse_op_view_info()

345 346 347
        # parse has_custom_verify
        self.custom_verify = self.parse_custom_verify()

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        # parse forward input name list and attribute name list
        self.forward_input_name_list = self.parse_forward_input_name()

    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

365 366 367 368 369 370 371 372 373
    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(type_list) == len(
                optional_list
            ), "type list size != optional list size."

374 375 376 377 378
    def parse_custom_verify(self):
        if 'custom_verify' in self.op_yaml_item:
            return self.op_yaml_item['custom_verify']
        return False

379
    def parse_op_phi_name(self):
380 381 382
        if (self.parse_op_inplace_info() is None) and (
            self.parse_op_view_info() is None
        ):
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
            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

398 399 400 401 402
    def parse_op_view_info(self):
        if 'view' in self.op_yaml_item:
            return self.op_yaml_item['view']
        return None

403 404 405 406 407 408 409 410 411 412 413 414 415
    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 'data_type' in self.op_compat_item['scalar'][scalar_attr]:
                    if (
416 417
                        scalar_attr == "depth"
                        and self.op_phi_name[0] == "one_hot"
418
                    ):
419
                        mutable_attribute_name_list.append("num_classes")
420
                    else:
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
                        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 = "float"
                    mutable_attribute_type_list.append(
                        [
                            "paddle::dialect::ScalarAttribute",
                            data_type,
                        ]
                    )
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
                # 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']:
                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'
                        ],
                    ]
                )
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
        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_nutable_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,
        )
510

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    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[]': 'ir::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_optional_list(self):
        optional_list = []
        for input_info in self.op_yaml_item['inputs']:
533 534 535 536
            if input_info['optional']:
                optional_list.append("true")
            else:
                optional_list.append("false")
537 538
        return optional_list

539 540 541 542 543 544 545 546 547
    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

548 549 550 551 552 553 554 555 556 557
    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[]': 'ir::VectorType<paddle::dialect::DenseTensorType>',
558
            'SelectedRows': 'paddle::dialect::SelectedRowsType',
559 560 561 562 563 564 565 566 567
        }
        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

568 569 570 571 572 573 574 575 576
    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

577 578 579 580
    def parse_output_optional_list(self):
        optional_list = []
        for output_info in self.op_yaml_item['outputs']:
            if 'optional' in output_info:
581 582 583 584
                if output_info['optional']:
                    optional_list.append("true")
                else:
                    optional_list.append("false")
585
            else:
586
                optional_list.append("false")
587 588
        return optional_list

589 590 591 592 593 594 595 596 597 598 599 600
    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

601 602 603 604 605 606
    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

607 608 609 610 611 612 613 614 615 616 617 618
    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']
619 620 621 622 623 624 625 626 627 628 629 630 631
                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'
                    ]
632 633
            if 'IntArray' in temp_type:
                if 'data_type' in attribute_info:
Y
YuanRisheng 已提交
634
                    temp_type = "const " + attribute_info['data_type'] + "&"
635 636 637
            type_list.append(self.get_phi_dtype_name(temp_type))
        return type_list

C
Chen Zhiyang 已提交
638 639 640 641 642 643 644 645 646 647 648
    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

649 650 651 652
    def parse_attribute_type_list(self):
        type_list = []
        for attribute_info in self.op_yaml_item['attrs']:
            assert (
653
                attribute_info['typename'] in self.attr_types_map
654
            ), f"{self.op_phi_name} : Attr type error."
655
            type_list.append(self.attr_types_map[attribute_info['typename']][0])
656 657
        return type_list

658 659 660 661 662 663 664 665 666
    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

667 668 669 670 671 672 673 674
    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)
                )
675
            else:
676 677
                default_value_list.append(None)
        return default_value_list
678

679 680 681 682 683 684 685 686 687 688 689 690
    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

691 692 693 694 695 696
    def parse_backward_name(self):
        if 'backward' in self.op_yaml_item:
            return self.op_yaml_item['backward']
        else:
            return None

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    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",
                "XPUPlace",
                "IPUPlace",
                "CustomPlace",
            )
        ):
            return "phi::" + name
        return name
715 716 717 718 719 720 721 722 723 724


def to_pascal_case(s):
    words = s.split("_")
    if s[-1] == "_":
        return "".join([word.capitalize() for word in words]) + "_"
    else:
        return "".join([word.capitalize() for word in words]) + ""


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
def OpInputGradSemanticCheck(op_info, op_info_items):
    input_grad_semantic_list = []
    num_inputs = len(op_info.input_name_list)

    # get backward op
    bwd_op_name = op_info.backward_name
    if (bwd_op_name is None) or (bwd_op_name not in op_info_items.keys()):
        input_grad_semantic_list = ["false" for i in range(num_inputs)]
    else:
        bwd_op_info = op_info_items[bwd_op_name]

        # cut "_grad" of each output of bwd_op, and then compare each modified output with corresponding input
        # thus determine whether each input has grad semantic
        bwd_output_list = bwd_op_info.output_name_list
        bwd_output_list_new = []
        for bwd_output in bwd_output_list:
            bwd_output_list_new.append(bwd_output[:-5])  # cut _grad

        bwd_fwd_input_list = bwd_op_info.forward_input_name_list
        if bwd_fwd_input_list is not None:
            assert (
                len(bwd_fwd_input_list) == num_inputs
            ), "Configuration of forward op and backward op is not match."
            for i in range(num_inputs):
                if bwd_fwd_input_list[i] in bwd_output_list_new:
                    input_grad_semantic_list.append("true")
                else:
                    input_grad_semantic_list.append("false")
        else:
            input_grad_semantic_list = ["false" for i in range(num_inputs)]

    return input_grad_semantic_list


def OpMutableAttributeGradSemanticCheck(op_info, op_info_items):
    mutable_attribute_grad_semantic_list = []
    fwd_mutable_attribute_list = op_info.mutable_attribute_name_list

    # get backward op
    bwd_op_name = op_info.backward_name
    if (bwd_op_name is None) or (bwd_op_name not in op_info_items.keys()):
        mutable_attribute_grad_semantic_list = [
            "false" for i in range(len(fwd_mutable_attribute_list))
        ]
    else:
        bwd_op_info = op_info_items[bwd_op_name]

        # cut "_grad" of each output of bwd_op, and then compare each modified output with corresponding attribute
        # thus determine whether each attribute has grad semantic
        bwd_output_list = bwd_op_info.output_name_list
        bwd_output_list_new = []
        for bwd_output in bwd_output_list:
            bwd_output_list_new.append(bwd_output[:-5])

        for i in range(len(fwd_mutable_attribute_list)):
            if fwd_mutable_attribute_list[i] in bwd_output_list_new:
                mutable_attribute_grad_semantic_list.append("true")
            else:
                mutable_attribute_grad_semantic_list.append("false")

    return mutable_attribute_grad_semantic_list


788 789
def OpGenerator(
    op_yaml_files,
790
    op_compat_yaml_file,
791 792 793 794
    namespaces,
    dialect_name,
    op_def_h_file,
    op_def_cc_file,
795
    op_vjp_cc_file,
796 797 798 799 800 801 802 803
):
    # (1) Prepare: Delete existing old files: pd_op.h.tmp, pd_op.cc.tmp
    if os.path.exists(op_def_h_file):
        os.remove(op_def_h_file)
    if os.path.exists(op_def_cc_file):
        os.remove(op_def_cc_file)

    # (2) Prepare: Get all op item in all op_yaml_files
804 805
    op_compat_parser = OpCompatParser(op_compat_yaml_file)

806 807 808 809 810
    op_yaml_items = []
    for yaml_file in op_yaml_files:
        with open(yaml_file, "r") as f:
            ops = yaml.safe_load(f)
            op_yaml_items = op_yaml_items + ops
811
    op_info_items = {}
812
    for op in op_yaml_items:
813 814
        op_info_items[op['name']] = OpInfoParser(
            op, op_compat_parser.get_compat(op['name'])
815
        )
816 817 818 819
    # (3) CodeGen: Traverse op_info_items and generate
    ops_name_list = []  # all op class name store in this list
    ops_declare_list = []  # all op class declare store in this list
    ops_defined_list = []  # all op class defined store in this list
820
    ops_vjp_defined_list = []  # all op vjp static interface defination
821
    for key, op_info in op_info_items.items():
822
        # get op inputs info
823 824 825
        op_input_name_list = op_info.input_name_list
        op_input_type_list = op_info.input_type_list
        op_input_optional_list = op_info.input_optional_list
826
        op_input_no_need_buffer_list = op_info.input_no_need_buffer_list
827
        # get op outputs info
828 829
        op_output_name_list = op_info.output_name_list
        op_output_type_list = op_info.output_type_list
830
        op_output_size_list = op_info.output_size_list
831
        op_output_optional_list = op_info.output_optional_list
832
        op_output_intermediate_list = op_info.output_intermediate_list
833 834 835 836
        # get op mutable attribute
        op_mutable_attribute_name_list = op_info.mutable_attribute_name_list
        op_mutable_attribute_type_list = op_info.mutable_attribute_type_list
        # get op attribute
837 838
        op_attribute_name_list = op_info.attribute_name_list
        op_attribute_type_list = op_info.attribute_type_list
839
        op_attribute_data_type_list = op_info.attribute_data_type_list
840 841
        op_attribute_build_arg_type_list = op_info.attribute_build_arg_type_list
        op_attribute_default_value_list = op_info.attribute_default_value_list
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
        op_non_mutable_attribute_name_list = (
            op_info.non_mutable_attribute_name_list
        )
        op_non_mutable_attribute_type_list = (
            op_info.non_mutable_attribute_type_list
        )
        op_non_mutable_attribute_data_type_list = (
            op_info.non_mutable_attribute_data_type_list
        )
        op_non_mutable_attribute_build_arg_type_list = (
            op_info.non_mutable_attribute_build_arg_type_list
        )
        op_non_mutable_attribute_default_value_list = (
            op_info.non_mutable_attribute_default_value_list
        )

858
        # others
859 860
        op_infer_meta_map = op_info.infer_meta_map
        op_kernel_map = op_info.kernel_map
861 862
        op_inplace_map = op_info.inplace_map
        op_view_map = op_info.view_map
863
        op_interfaces = ["paddle::dialect::OpYamlInfoInterface"]
864 865
        op_traits = []

866
        if op_info.infer_meta_func:
867
            op_interfaces += ["paddle::dialect::InferMetaInterface"]
868

869 870
        if (
            op_info.backward_name
871
            and op_info.op_phi_name[0] in vjp_interface_declare_gen_op_list
872
        ):
873
            op_interfaces += ["paddle::dialect::VjpInterface"]
874
        exclusive_interface_str = gen_exclusive_interface_str(op_info)
H
hong 已提交
875

876 877 878 879 880 881 882 883
        # check op inputs and mutable_attributes grad semantics
        input_grad_semantic_list = OpInputGradSemanticCheck(
            op_info, op_info_items
        )
        mutable_attribute_grad_semantic_list = (
            OpMutableAttributeGradSemanticCheck(op_info, op_info_items)
        )

884 885
        # If op has inplace info, we will generate inplace op and non-inplace op.
        for op_name in op_info.op_phi_name:
886 887
            if op_name in _NO_NEED_GEN_OPS:
                continue
888 889 890
            op_class_name = to_pascal_case(op_name) + "Op"
            op_dialect_name = dialect_name + "." + op_name

891 892 893
            # =================================== #
            #    gen interface/trait list str     #
            # =================================== #
894 895 896
            op_interfaces_str = ""
            if len(op_interfaces) > 0:
                op_interfaces_str = "," + ",".join(op_interfaces)
897 898

            if op_name[-1] == "_":
899
                op_traits += ["paddle::dialect::InplaceTrait"]
900

901 902 903 904
            op_traits_str = ""
            if len(op_traits) > 0:
                op_traits_str = "," + ",".join(op_traits)

905 906 907
            # =================================== #
            #  gen get input/output methods str   #
            # =================================== #
908 909 910 911 912
            op_get_inputs_outputs_str = gen_op_get_inputs_outputs_str(
                op_input_name_list,
                op_mutable_attribute_name_list,
                op_output_name_list,
            )
913

914 915 916 917 918 919
            # =================================== #
            #         gen Build methods str       #
            # =================================== #
            build_args_with_muta_attr_not_input_for_declare = ""
            build_func_with_muta_attr_not_input = ""
            build_mutable_attr_is_input = ""
920 921
            build_attr_num_over_1 = ""
            build_func_with_attr_is_map = ""
922 923
            build_func_with_muta_attr_is_input = ""

924
            if op_infer_meta_map is not None:
925 926 927
                (
                    build_args_with_muta_attr_not_input_for_declare,
                    build_func_with_muta_attr_not_input,
928
                ) = gen_build_func_str(
929
                    op_class_name,
930
                    op_input_name_list,
931 932
                    op_input_type_list,
                    op_attribute_name_list,
933
                    op_attribute_type_list,
934 935
                    op_attribute_build_arg_type_list,
                    op_attribute_default_value_list,
936
                    op_mutable_attribute_name_list,
937
                    op_mutable_attribute_type_list,
938
                    op_non_mutable_attribute_name_list,
939
                    op_non_mutable_attribute_type_list,
940 941
                    op_non_mutable_attribute_build_arg_type_list,
                    op_non_mutable_attribute_default_value_list,
942 943 944 945
                    op_output_name_list,
                    op_output_type_list,
                    op_output_size_list,
                    op_infer_meta_map,
946
                    muta_attr_is_input=False,
947
                )
Z
zhangbo9674 已提交
948
                if len(op_attribute_name_list) > 0:
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
                    (
                        build_args_with_attr_is_map_for_declare,
                        build_func_with_attr_is_map,
                    ) = gen_build_func_str(
                        op_class_name,
                        op_input_name_list,
                        op_input_type_list,
                        op_attribute_name_list,
                        op_attribute_type_list,
                        op_attribute_build_arg_type_list,
                        op_attribute_default_value_list,
                        op_mutable_attribute_name_list,
                        op_mutable_attribute_type_list,
                        op_non_mutable_attribute_name_list,
                        op_non_mutable_attribute_type_list,
                        op_non_mutable_attribute_build_arg_type_list,
                        op_non_mutable_attribute_default_value_list,
                        op_output_name_list,
                        op_output_type_list,
                        op_output_size_list,
                        op_infer_meta_map,
                        muta_attr_is_input=False,
                        attr_args_is_map=True,
                    )
                    build_attr_num_over_1 = (
                        "static void Build({build_args});".format(
                            build_args=build_args_with_attr_is_map_for_declare
                        )
                    )

979
                if len(op_mutable_attribute_name_list) > 0:
980 981 982
                    (
                        build_args_with_muta_attr_is_input_for_declare,
                        build_func_with_muta_attr_is_input,
983
                    ) = gen_build_func_str(
984 985 986 987
                        op_class_name,
                        op_input_name_list,
                        op_input_type_list,
                        op_attribute_name_list,
988
                        op_attribute_type_list,
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
                        op_attribute_build_arg_type_list,
                        op_attribute_default_value_list,
                        op_mutable_attribute_name_list,
                        op_mutable_attribute_type_list,
                        op_non_mutable_attribute_name_list,
                        op_non_mutable_attribute_type_list,
                        op_non_mutable_attribute_build_arg_type_list,
                        op_non_mutable_attribute_default_value_list,
                        op_output_name_list,
                        op_output_type_list,
                        op_output_size_list,
                        op_infer_meta_map,
                        muta_attr_is_input=True,
                    )

                    build_mutable_attr_is_input = "static void Build({build_args});".format(
                        build_args=build_args_with_muta_attr_is_input_for_declare
                    )
1007

1008
            # gen op_declare_str/op_defined_str
1009
            if len(op_non_mutable_attribute_name_list) == 0:
1010 1011 1012 1013 1014 1015 1016
                op_declare_str = OP_DECLARE_TEMPLATE.format(
                    op_name=op_class_name,
                    dialect_op_name=op_dialect_name,
                    interfaces=op_interfaces_str,
                    traits=op_traits_str,
                    attribute_declare=op_0_attribute_declare_str,
                    attribute_num=0,
1017 1018
                    build_args=build_args_with_muta_attr_not_input_for_declare,
                    build_mutable_attr_is_input=build_mutable_attr_is_input,
1019
                    build_attr_num_over_1=build_attr_num_over_1,
1020
                    get_inputs_and_outputs=op_get_inputs_outputs_str,
H
hong 已提交
1021
                    exclusive_interface=exclusive_interface_str,
1022 1023 1024 1025 1026 1027 1028 1029 1030
                )
                op_defined_str = ""
            else:
                op_declare_str = OP_DECLARE_TEMPLATE.format(
                    op_name=op_class_name,
                    dialect_op_name=op_dialect_name,
                    interfaces=op_interfaces_str,
                    traits=op_traits_str,
                    attribute_declare=op_n_attribute_declare_str.format(
1031
                        attribute_num=len(op_non_mutable_attribute_name_list)
1032
                    ),
1033
                    attribute_num=len(op_non_mutable_attribute_name_list),
1034 1035
                    build_args=build_args_with_muta_attr_not_input_for_declare,
                    build_mutable_attr_is_input=build_mutable_attr_is_input,
1036
                    build_attr_num_over_1=build_attr_num_over_1,
1037
                    get_inputs_and_outputs=op_get_inputs_outputs_str,
H
hong 已提交
1038
                    exclusive_interface=exclusive_interface_str,
1039 1040
                )
                attribute_names_str = (
1041
                    '"' + '", "'.join(op_non_mutable_attribute_name_list) + '"'
1042 1043 1044
                )
                op_defined_str = OP_N_ATTRIBUTE_DEFINED_TEMPLATE.format(
                    op_name=op_class_name,
1045
                    attribute_num=len(op_non_mutable_attribute_name_list),
1046 1047
                    attribute_names=attribute_names_str,
                )
1048

1049 1050 1051
            # =================================== #
            #         gen GetOpInfo func str      #
            # =================================== #
1052
            # generate get op info funciton: inputs
1053
            input_info_list = []
1054 1055 1056 1057 1058 1059 1060 1061
            for idx in range(len(op_input_name_list)):
                input_info_list.append(
                    CONSTRUCT_INPUT_INFO_TEMPLATE.format(
                        name=op_input_name_list[idx],
                        typename=op_input_type_list[idx],
                        optional=op_input_optional_list[idx],
                        no_need_buffer=op_input_no_need_buffer_list[idx],
                        is_mutable_attribute='false',
1062
                        with_grad_semantic=input_grad_semantic_list[idx],
1063
                    )
1064 1065 1066 1067 1068 1069 1070 1071 1072
                )
            for idx in range(len(op_mutable_attribute_name_list)):
                input_info_list.append(
                    CONSTRUCT_INPUT_INFO_TEMPLATE.format(
                        name=op_mutable_attribute_name_list[idx],
                        typename=op_mutable_attribute_type_list[idx][0],
                        optional='false',
                        no_need_buffer='false',
                        is_mutable_attribute='true',
1073 1074 1075
                        with_grad_semantic=mutable_attribute_grad_semantic_list[
                            idx
                        ],
1076
                    )
1077 1078 1079 1080 1081
                )
            if len(input_info_list) > 0:
                inputs_info_str = ", ".join(input_info_list)
            else:
                inputs_info_str = ""
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
            # generate get op info funciton: outputs
            outputs_info_str = ""
            if len(op_output_name_list) > 0:
                output_info_list = []
                for idx in range(len(op_output_name_list)):
                    output_info_list.append(
                        CONSTRUCT_OUTPUT_INFO_TEMPLATE.format(
                            name=op_output_name_list[idx],
                            typename=op_output_type_list[idx],
                            optional=op_output_optional_list[idx],
                            intermediate=op_output_intermediate_list[idx],
                        )
1094
                    )
1095 1096 1097
                outputs_info_str = ", ".join(output_info_list)
            # generate get op info funciton: attributes
            attribute_info_str = ""
1098
            if len(op_non_mutable_attribute_name_list) > 0:
1099
                attribute_info_list = []
1100
                for idx in range(len(op_non_mutable_attribute_name_list)):
1101 1102
                    attribute_info_list.append(
                        CONSTRUCT_ATTRIBUTE_INFO_TEMPLATE.format(
1103 1104 1105 1106 1107
                            name=op_non_mutable_attribute_name_list[idx],
                            typename=op_non_mutable_attribute_type_list[idx],
                            data_type=op_non_mutable_attribute_data_type_list[
                                idx
                            ],
1108
                        )
1109
                    )
1110
                attribute_info_str = ", ".join(attribute_info_list)
1111 1112 1113 1114 1115 1116
            # generate runtiem info
            infer_meta_func_str = ""
            infer_meta_param_str = ""
            if op_infer_meta_map is not None:
                infer_meta_func_str = op_infer_meta_map['func']
                infer_meta_param_str = '", "'.join(op_infer_meta_map['param'])
1117

1118 1119
            kernel_func_str = ""
            kernel_param_str = ""
1120
            kernel_key_dtype = ""
1121
            kernel_key_backend = ""
1122 1123 1124
            if op_kernel_map is not None:
                kernel_func_str = '", "'.join(op_kernel_map['func'])
                kernel_param_str = '", "'.join(op_kernel_map['param'])
1125 1126 1127 1128
                if 'data_type' in op_kernel_map and op_kernel_map['data_type']:
                    kernel_key_dtype = '", "'.join(
                        op_kernel_map['data_type']['candidates']
                    )
1129 1130
                    if kernel_key_dtype != "":
                        kernel_key_dtype = '"' + kernel_key_dtype + '"'
1131 1132 1133 1134 1135 1136
                if 'backend' in op_kernel_map and op_kernel_map['backend']:
                    kernel_key_backend = '", "'.join(
                        op_kernel_map['backend']['candidates']
                    )
                    if kernel_key_backend != "":
                        kernel_key_backend = '"' + kernel_key_backend + '"'
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
            inplace_str = ""
            view_str = ""
            if op_name[-1] == "_":
                if op_inplace_map is not None:
                    for key, value in op_inplace_map.items():
                        inplace_str += '{"' + key + '", "' + value + '"},'
                    inplace_str = inplace_str[:-1]
                if op_view_map is not None:
                    for key, value in op_view_map.items():
                        view_str += '{"' + key + '", "' + value + '"},'
                    view_str = view_str[:-1]

1150 1151 1152 1153 1154
            op_info_func_str = OP_INFO_TEMPLATE.format(
                op_name=op_class_name,
                inputs=inputs_info_str,
                attributes=attribute_info_str,
                outputs=outputs_info_str,
1155 1156 1157 1158
                infer_meta_func=infer_meta_func_str,
                infer_meta_param=infer_meta_param_str,
                kernel_func=kernel_func_str,
                kernel_param=kernel_param_str,
1159
                kernel_key_dtype=kernel_key_dtype,
1160
                kernel_key_backend=kernel_key_backend,
1161 1162
                inplace=inplace_str,
                view=view_str,
1163
                origin_op_name=op_info.op_yaml_item['name'],
1164
            )
1165

1166
            # generate op verify function str
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
            op_verify_str = ''
            if not op_info.custom_verify:
                op_verify_str = gen_verify_func_str(
                    op_class_name,
                    op_input_type_list,
                    op_input_optional_list,
                    op_mutable_attribute_name_list,
                    op_mutable_attribute_type_list,
                    op_non_mutable_attribute_name_list,
                    op_non_mutable_attribute_type_list,
                    op_output_type_list,
                    op_output_optional_list,
                )
1180

1181
            op_infer_meta_str = gen_op_infer_meta_str(op_info, op_class_name)
H
hong 已提交
1182

1183 1184 1185 1186 1187 1188
            # =================================== #
            #         gen Vjp func str      #
            # =================================== #

            # generate op vjp function str

1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
            op_vjp_str = ''
            if dialect_name == "cinn":
                logging.warning("cinn is currently not support Vjp function")
            else:
                # TODO(chenzhiyang) add vjp gen code
                if (
                    op_info.backward_name
                    and op_info.op_phi_name[0]
                    in vjp_interface_implementation_gen_op_list
                ):
                    op_vjp_str = gen_op_vjp_str(
                        op_class_name,
                        op_info.backward_name,
                        op_name,
                        op_info_items[op_info.op_phi_name[0]],
                        op_info_items[op_info.backward_name],
                    )
1206

1207 1208 1209 1210
            ops_name_list.append(op_class_name)
            ops_declare_list.append(op_declare_str)
            ops_defined_list.append(op_defined_str)
            ops_defined_list.append(op_info_func_str)
1211
            ops_defined_list.append(build_func_with_muta_attr_not_input)
1212
            ops_defined_list.append(build_func_with_attr_is_map)
1213 1214
            if len(op_mutable_attribute_name_list) > 0:
                ops_defined_list.append(build_func_with_muta_attr_is_input)
1215
            ops_defined_list.append(op_verify_str)
1216
            ops_defined_list.append(op_infer_meta_str)
1217 1218
            # NOTE(chenxi67)skip if dialect_name==cinn
            if dialect_name == "cinn":
1219
                pass
1220
            else:
1221
                ops_vjp_defined_list.append(op_vjp_str)
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232

    # (4) Generate head file str
    op_namespaces_prev = ""
    for name in namespaces:
        op_namespaces_prev += name + "::"
    ops_name_with_namespace_list = []
    for name in ops_name_list:
        ops_name_with_namespace_list.append(op_namespaces_prev + name)
    op_list_str = GET_OP_LIST_TEMPALTE.format(
        ", ".join(ops_name_with_namespace_list)
    )  # Add GET_OP_LIST
1233 1234 1235 1236 1237

    declare_type_id_str = ""
    for op in ops_name_with_namespace_list:
        declare_type_id_str += DECLARE_OP_TYPE_ID.format(op_name=op)

1238 1239 1240 1241 1242 1243 1244
    head_file_str = ""
    head_file_str += "".join(ops_declare_list)  # Add op class
    for name in reversed(namespaces):
        head_file_str = NAMESPACE_GARD_TEMPLATE.format(
            namespace=name, input=head_file_str
        )  # Add namespaces
    head_file_str = H_FILE_TEMPLATE.format(
1245 1246 1247
        op_declare=op_list_str,
        input=head_file_str,
        declare_type_id=declare_type_id_str,
1248 1249 1250 1251 1252 1253 1254 1255
    )  # Add head

    # (5) Generate source file str
    source_file_str = "".join(ops_defined_list)  # Add op define
    for name in reversed(namespaces):
        source_file_str = NAMESPACE_GARD_TEMPLATE.format(
            namespace=name, input=source_file_str
        )  # Add namespaces
1256 1257 1258 1259 1260

    define_type_id_str = ""
    for op in ops_name_with_namespace_list:
        define_type_id_str += DEFINE_OP_TYPE_ID.format(op_name=op)

1261
    source_file_str = CC_FILE_TEMPLATE.format(
1262 1263 1264
        h_file=op_def_h_file[:-4],
        input=source_file_str,
        define_type_id=define_type_id_str,
1265 1266
    )  # Add head

1267 1268 1269
    vjp_source_file_str = VJP_CC_FILE_TEMPLATE.format(
        input="".join(ops_vjp_defined_list)
    )
1270
    # (5) Generate pd_op.h.tmp, pd_op.cc.tmp
1271
    with open(op_def_h_file, 'w') as f:
1272
        f.write(head_file_str)
1273
    with open(op_def_cc_file, 'w') as f:
1274
        f.write(source_file_str)
1275 1276 1277 1278 1279
    # NOTE(Aurelius84): op_gen.py is called multiply times,
    # and vjp is only avaible for pd dialect.
    if dialect_name != 'cinn' and op_vjp_cc_file:
        with open(op_vjp_cc_file, 'w') as f:
            f.write(vjp_source_file_str)
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294


# =====================================
# Script parameter parsing
# =====================================
def ParseArguments():
    parser = argparse.ArgumentParser(
        description='Generate Dialect OP Definition Files By Yaml'
    )
    parser.add_argument('--op_yaml_files', type=str)
    parser.add_argument('--op_compat_yaml_file', type=str)
    parser.add_argument('--namespaces', type=str)
    parser.add_argument('--dialect_name', type=str)
    parser.add_argument('--op_def_h_file', type=str)
    parser.add_argument('--op_def_cc_file', type=str)
1295
    parser.add_argument('--op_vjp_cc_file', type=str)
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    return parser.parse_args()


# =====================================
# Main
# =====================================
if __name__ == "__main__":
    # parse arguments
    args = ParseArguments()
    op_yaml_files = args.op_yaml_files.split(",")
    op_compat_yaml_file = args.op_compat_yaml_file
    namespaces = []
    if args.namespaces is not None:
        namespaces = args.namespaces.split(",")
    dialect_name = args.dialect_name
    op_def_h_file = args.op_def_h_file
    op_def_cc_file = args.op_def_cc_file
1313
    op_vjp_cc_file = args.op_vjp_cc_file
1314 1315 1316 1317

    # auto code generate
    OpGenerator(
        op_yaml_files,
1318
        op_compat_yaml_file,
1319 1320 1321 1322
        namespaces,
        dialect_name,
        op_def_h_file,
        op_def_cc_file,
1323
        op_vjp_cc_file,
1324
    )