api_base.py 55.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2021 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.

15
import collections
16
import re
17

18
PREFIX_TENSOR_NAME = 'input_'
19 20 21
PREFIX_META_TENSOR_NAME = 'meta_'


22
class BaseAPI:
23 24 25 26 27 28 29 30 31 32 33 34
    def __init__(self, api_item_yaml):
        self.api = self.get_api_name(api_item_yaml)

        # inputs:
        #     names : [], list of input names
        #     input_info : {input_name : type}
        # attrs:
        #     names : [], list of attribute names
        #     attr_info : { attr_name : (type, default_values)}
        # outputs:
        #     names : [], list of output names
        #     types : [], list of output types
35
        #     out_size_expr : [], expression for getting size of vector<Tensor>
36 37 38 39 40 41
        (
            self.inputs,
            self.attrs,
            self.outputs,
            self.optional_vars,
        ) = self.parse_args(self.api, api_item_yaml)
42 43

        self.is_base_api = True
X
xiaoguoguo626807 已提交
44
        self.is_only_composite_api = False
45 46 47 48
        if 'invoke' in api_item_yaml:
            self.is_base_api = False
            self.invoke = api_item_yaml['invoke']
        else:
49
            if 'infer_meta' in api_item_yaml:
50
                self.infer_meta = self.parse_infer_meta(
51 52
                    api_item_yaml['infer_meta']
                )
X
xiaoguoguo626807 已提交
53 54 55 56 57 58
            if 'composite' in api_item_yaml and 'kernel' not in api_item_yaml:
                self.is_base_api = False
                self.is_only_composite_api = True
                self.kernel = None
            else:
                self.kernel = self.parse_kernel(api_item_yaml['kernel'])
59
            self.data_transform = self.parse_data_transform(api_item_yaml)
60
            self.inplace_map, self.view_map = {}, {}
61

Y
YuanRisheng 已提交
62 63 64
        self.gene_input_func = {
            "const Tensor&": {
                "dense": self.gene_dense_input,
65
                "selected_rows": self.gene_selected_rows_input,
Y
YuanRisheng 已提交
66 67 68
            },
            "const paddle::optional<Tensor>&": {
                "dense": self.gene_dense_input,
69
                "selected_rows": self.gene_selected_rows_input,
Y
YuanRisheng 已提交
70
            },
71
            "const std::vector<Tensor>&": {"dense": self.gene_vec_dense_input},
Y
YuanRisheng 已提交
72 73
            "const paddle::optional<std::vector<Tensor>>&": {
                "dense": self.gene_optional_vec_dense_input
74
            },
Y
YuanRisheng 已提交
75 76
        }

77
    def get_api_name(self, api_item_yaml):
78
        return api_item_yaml['op']
79

80 81 82
    def get_api_func_name(self):
        return self.api

83 84 85
    def get_input_tensor_args(self, inplace_flag=False):
        input_args = []
        inplace_type_map = {
86 87 88 89
            "const Tensor&": "Tensor&",
            "const paddle::optional<Tensor>&": "paddle::optional<Tensor>&",
            "const std::vector<Tensor>&": "std::vector<Tensor>&",
            "const paddle::optional<std::vector<Tensor>>&": "paddle::optional<std::vector<Tensor>>&",
90 91 92 93
        }
        for name in self.inputs['names']:
            name = name.split('@')[0]
            if inplace_flag and name in self.inplace_map.values():
94
                input_args.append(
95 96 97 98
                    inplace_type_map[self.inputs['input_info'][name]]
                    + ' '
                    + name
                )
99 100 101 102 103 104 105 106 107 108
            else:
                input_args.append(self.inputs['input_info'][name] + ' ' + name)
        return input_args

    def get_declare_args(self, inplace_flag=False):
        declare_args = self.get_input_tensor_args(inplace_flag)
        for name in self.attrs['names']:
            default_value = ''
            if self.attrs['attr_info'][name][1] is not None:
                default_value = ' = ' + self.attrs['attr_info'][name][1]
109 110 111
            declare_args.append(
                self.attrs['attr_info'][name][0] + ' ' + name + default_value
            )
112

113 114 115 116 117 118 119 120
        return ", ".join(declare_args)

    def get_define_args(self, inplace_flag=False):
        define_args = self.get_input_tensor_args(inplace_flag)
        for name in self.attrs['names']:
            define_args.append(self.attrs['attr_info'][name][0] + ' ' + name)

        return ", ".join(define_args)
121

122
    def parse_args(self, api_name, api_item_yaml):
123 124 125 126 127
        optional_vars = []
        if 'optional' in api_item_yaml:
            optional_vars = [
                item.strip() for item in api_item_yaml['optional'].split(',')
            ]
128 129 130
        inputs, attrs = self.parse_input_and_attr(
            api_name, api_item_yaml['args'], optional_vars
        )
131
        output_type_list, output_names, out_size_expr = self.parse_output(
132 133 134 135 136 137 138 139 140 141 142 143
            api_name, api_item_yaml['output']
        )
        return (
            inputs,
            attrs,
            {
                'names': output_names,
                'types': output_type_list,
                'out_size_expr': out_size_expr,
            },
            optional_vars,
        )
144

145
    def parse_input_and_attr(self, api_name, args_config, optional_vars=[]):
146 147 148
        inputs = {'names': [], 'input_info': {}}
        attrs = {'names': [], 'attr_info': {}}
        args_str = args_config.strip()
149 150 151
        assert args_str.startswith('(') and args_str.endswith(
            ')'
        ), f"Args declaration should start with '(' and end with ')', please check the args of {api_name} in yaml."
152
        args_str = args_str[1:-1]
153 154 155
        patten = re.compile(r',(?![^{]*\})')  # support int[] a={1,3}
        args_list = re.split(patten, args_str.strip())
        args_list = [x.strip() for x in args_list]
Z
zyfncg 已提交
156 157
        input_types_map = {
            'Tensor': 'const Tensor&',
158
            'Tensor[]': 'const std::vector<Tensor>&',
Z
zyfncg 已提交
159
        }
160
        attr_types_map = {
161
            'IntArray': 'const IntArray&',
162
            'Scalar': 'const Scalar&',
163 164 165 166
            'Scalar(int)': 'const Scalar&',
            'Scalar(int64_t)': 'const Scalar&',
            'Scalar(float)': 'const Scalar&',
            'Scalar(dobule)': 'const Scalar&',
167
            'Scalar[]': 'const std::vector<phi::Scalar>&',
168
            'int': 'int',
169 170
            'int32_t': 'int32_t',
            'int64_t': 'int64_t',
171 172 173
            'long': 'long',
            'size_t': 'size_t',
            'float': 'float',
174
            'float[]': 'const std::vector<float>&',
175 176
            'double': 'double',
            'bool': 'bool',
177
            'bool[]': 'const std::vector<bool>&',
178
            'str': 'const std::string&',
179
            'str[]': 'const std::vector<std::string>&',
180
            'Place': 'const Place&',
181 182
            'DataLayout': 'DataLayout',
            'DataType': 'DataType',
183
            'int64_t[]': 'const std::vector<int64_t>&',
Z
zhiboniu 已提交
184
            'int[]': 'const std::vector<int>&',
185 186
        }
        optional_types_trans = {
187
            'Tensor': 'const paddle::optional<Tensor>&',
188 189
            'Tensor[]': 'const paddle::optional<std::vector<Tensor>>&',
            'int': 'paddle::optional<int>',
190 191
            'int32_t': 'paddle::optional<int32_t>',
            'int64_t': 'paddle::optional<int64_t>',
192 193 194
            'float': 'paddle::optional<float>',
            'double': 'paddle::optional<double>',
            'bool': 'paddle::optional<bool>',
195
            'Place': 'paddle::optional<const Place&>',
196
            'DataLayout': 'paddle::optional<DataLayout>',
197
            'DataType': 'paddle::optional<DataType>',
198 199
        }

200 201
        for item in args_list:
            item = item.strip()
Z
zyfncg 已提交
202
            type_and_name = item.split(' ')
203 204
            # match the input tensor
            has_input = False
Z
zyfncg 已提交
205 206 207
            for in_type_symbol, in_type in input_types_map.items():
                if type_and_name[0] == in_type_symbol:
                    input_name = type_and_name[1].strip()
208 209 210 211 212 213
                    assert (
                        len(input_name) > 0
                    ), f"The input tensor name should not be empty. Please check the args of {api_name} in yaml."
                    assert (
                        len(attrs['names']) == 0
                    ), f"The input Tensor should appear before attributes. please check the position of {api_name}:input({input_name}) in yaml"
214

215 216 217
                    if input_name in optional_vars:
                        in_type = optional_types_trans[in_type_symbol]

218 219 220 221 222 223 224 225
                    inputs['names'].append(input_name)
                    inputs['input_info'][input_name] = in_type
                    has_input = True
                    break
            if has_input:
                continue

            # match the attribute
Z
zyfncg 已提交
226 227
            for attr_type_symbol, attr_type in attr_types_map.items():
                if type_and_name[0] == attr_type_symbol:
228 229 230 231
                    attr_name = item[len(attr_type_symbol) :].strip()
                    assert (
                        len(attr_name) > 0
                    ), f"The attribute name should not be empty. Please check the args of {api_name} in yaml."
232 233 234 235 236 237
                    default_value = None
                    if '=' in attr_name:
                        attr_infos = attr_name.split('=')
                        attr_name = attr_infos[0].strip()
                        default_value = attr_infos[1].strip()

238 239 240
                    if attr_name in optional_vars:
                        attr_type = optional_types_trans[attr_type_symbol]

241 242 243
                    default_value_str = (
                        "" if default_value is None else '=' + default_value
                    )
244 245 246 247
                    attrs['names'].append(attr_name)
                    attrs['attr_info'][attr_name] = (attr_type, default_value)
                    break

248
        return inputs, attrs
249 250 251

    def parse_output(self, api_name, output_config):
        def parse_output_item(output_item):
Z
zyfncg 已提交
252 253
            output_type_map = {
                'Tensor': 'Tensor',
254
                'Tensor[]': 'std::vector<Tensor>',
Z
zyfncg 已提交
255
            }
256 257
            result = re.search(
                r"(?P<out_type>[a-zA-Z0-9_[\]]+)\s*(?P<name>\([a-zA-Z0-9_@]+\))?\s*(?P<expr>\{[^\}]+\})?",
258 259 260 261 262
                output_item,
            )
            assert (
                result is not None
            ), f"{api_name} : the output config parse error."
263
            out_type = result.group('out_type')
264 265 266
            assert (
                out_type in output_type_map
            ), f"{api_name} : Output type error: the output type only support Tensor and Tensor[], \
267 268
                  but now is {out_type}."

269 270 271 272 273 274 275 276 277 278
            out_name = (
                'out'
                if result.group('name') is None
                else result.group('name')[1:-1]
            )
            out_size_expr = (
                None
                if result.group('expr') is None
                else result.group('expr')[1:-1]
            )
279
            return output_type_map[out_type], out_name, out_size_expr
280 281 282 283

        temp_list = output_config.split(',')

        if len(temp_list) == 1:
284
            out_type, out_name, size_expr = parse_output_item(temp_list[0])
285
            return [out_type], [out_name], [size_expr]
286 287 288
        else:
            out_type_list = []
            out_name_list = []
289
            out_size_expr_list = []
290
            for output_item in temp_list:
291
                out_type, out_name, size_expr = parse_output_item(output_item)
292 293
                out_type_list.append(out_type)
                out_name_list.append(out_name)
294
                out_size_expr_list.append(size_expr)
295

296
            return out_type_list, out_name_list, out_size_expr_list
297

298 299 300 301 302 303 304 305 306 307 308 309 310 311
    def parse_infer_meta(self, infer_meta_config):
        infer_meta = infer_meta_config
        if 'param' not in infer_meta_config:
            infer_meta['param'] = None

        return infer_meta

    def parse_kernel(self, kernel_config):
        # kernel :
        #    func : [], Kernel functions (example: scale, scale_sr)
        #    param : [], Input params of kernel
        #    backend : str, the names of param to choose the kernel backend, default is None
        #    layout : str, the names of param to choose the kernel layout, default is None
        #    data_type : str, the names of param to choose the kernel data_type, default is None
312
        #    dispatch : {}, the key is kernel_func, the value is type of inputs and outputs for kernel (example: {kernel_name : (['dense','sparse_coo']#input,['sparse_coo']#output)})
313 314 315 316 317
        kernel = {
            'func': [],
            'param': None,
            'backend': None,
            'layout': None,
Z
zyfncg 已提交
318
            'data_type': None,
319
            'dispatch': {},
320 321 322 323 324 325 326 327 328
        }
        if 'backend' in kernel_config and len(kernel_config['backend']) > 0:
            kernel['backend'] = kernel_config['backend']
        if 'layout' in kernel_config and len(kernel_config['layout']) > 0:
            kernel['layout'] = kernel_config['layout']
        if 'data_type' in kernel_config and len(kernel_config['data_type']) > 0:
            kernel['data_type'] = kernel_config['data_type']
        if 'param' in kernel_config:
            kernel['param'] = kernel_config['param']
329
        kernel_funcs = re.compile(r'([a-zA-Z0-9_]+)\s*({[^}]+})?').findall(
330 331
            kernel_config['func']
        )
332 333 334 335 336 337 338

        def parse_kernel_in_out_type(in_out_str):
            if len(in_out_str) == 0:
                return None
            tmp_in_out_list = in_out_str[1:-1].split('->')
            inputs = [item.strip() for item in tmp_in_out_list[0].split(',')]
            outputs = [item.strip() for item in tmp_in_out_list[1].split(',')]
339 340 341 342

            # check the tensor type
            for item in inputs:
                assert item in [
343 344 345 346
                    'dense',
                    'selected_rows',
                    'sparse_coo',
                    'sparse_csr',
347 348 349
                ], f"{self.api} : Invalid input tensor type ('{item}'), here we only support 'dense', 'selected_rows', 'sparse_coo' and 'sparse_csr'."
            for item in outputs:
                assert item in [
350 351 352 353
                    'dense',
                    'selected_rows',
                    'sparse_coo',
                    'sparse_csr',
354 355
                ], f"{self.api} : Invalid output tensor type ('{item}'), here we only support 'dense', 'selected_rows', 'sparse_coo' and 'sparse_csr'."

356 357 358 359 360
            return (inputs, outputs)

        for func_item in kernel_funcs:
            kernel['func'].append(func_item[0])
            kernel['dispatch'][func_item[0]] = parse_kernel_in_out_type(
361 362
                func_item[1]
            )
363 364 365 366 367 368 369 370

        return kernel

    def parse_data_transform(self, api_item_yaml):
        data_transform = {'skip_transform': [], 'support_trans_dtype': []}
        if 'data_transform' in api_item_yaml:
            if 'skip_transform' in api_item_yaml['data_transform']:
                data_transform['skip_transform'] = api_item_yaml[
371 372
                    'data_transform'
                ]['skip_transform']
373 374
            if 'support_trans_dtype' in api_item_yaml['data_transform']:
                data_transform['support_trans_dtype'] = api_item_yaml[
375 376
                    'data_transform'
                ]['support_trans_dtype']
377 378 379

        return data_transform

380
    # Override by child class
381
    def get_return_type(self, inplace_flag=False):
382 383 384
        return None

    def gene_api_declaration(self):
385 386 387 388 389
        api_declaration = ""
        api_func_name = self.get_api_func_name()
        if api_func_name[-1] != '_':
            api_declaration = f"""
PADDLE_API {self.get_return_type()} {api_func_name}({self.get_declare_args()});
390 391
"""

392 393 394
        if self.is_base_api and len(self.inplace_map) > 0:
            if api_func_name[-1] != '_':
                api_func_name += '_'
395 396 397
            api_declaration = (
                api_declaration
                + f"""
398
PADDLE_API {self.get_return_type(inplace_flag=True)} {api_func_name}({self.get_declare_args(inplace_flag=True)});
399
"""
400
            )
401 402 403

        return api_declaration

404 405 406 407 408 409
    # Backward API Override this method
    def gene_kernel_backend_select(self):
        backend_select_code = ""
        if self.kernel['backend'] is not None:
            if '>' in self.kernel['backend']:
                vars_list = self.kernel['backend'].split('>')
410 411 412 413 414 415 416
                assert (
                    len(vars_list) == 2
                ), f"{self.api} api: The number of params to set backend with '>' only allows 2, but received {len(vars_list)}."
                assert (vars_list[0].strip() in self.attrs['names']) and (
                    self.attrs['attr_info'][vars_list[0].strip()][0]
                    == 'const Place&'
                ), f"{self.api} api: When use '>' to set kernel backend, the first param should be a attribute with Place type."
417 418 419 420 421 422 423 424 425 426 427 428 429 430
                backend_select_code = f"""
  kernel_backend = ParseBackendWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});
"""

            else:
                backend_args = [
                    ele.strip() for ele in self.kernel['backend'].split(',')
                ]
                backend_select_code = f"""
  kernel_backend = ParseBackend({", ".join(backend_args)});
"""

        return backend_select_code

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    def gene_kernel_select(self) -> str:
        api = self.api
        input_names = self.inputs['names']
        attrs = self.attrs
        kernel = self.kernel

        kernel_key_item_init = """
  Backend kernel_backend = Backend::UNDEFINED;
  DataLayout kernel_layout = DataLayout::UNDEFINED;
  DataType kernel_data_type = DataType::UNDEFINED;
"""
        # Check the tensor options
        attr_backend_count = 0
        attr_layout_count = 0
        attr_data_type_count = 0
        for attr_name in attrs['names']:
447
            if attrs['attr_info'][attr_name][0] == 'const Place&':
448 449 450
                assert (
                    kernel['backend'] is not None
                ), f"{api} api: When there is a parameter with 'Place' type in attributes, you must set backend of kernel manually."
451 452
                attr_backend_count = attr_backend_count + 1
            if attrs['attr_info'][attr_name][0] == 'DataLayout':
453 454 455
                assert (
                    kernel['layout'] is not None
                ), f"{api} api: When there is a parameter with 'DataLayout' type in attributes, you must set layout of kernel manually."
456 457
                attr_layout_count = attr_layout_count + 1
            if attrs['attr_info'][attr_name][0] == 'DataType':
458 459 460
                assert (
                    kernel['data_type'] is not None
                ), f"{api} api: When there is a parameter with 'DataType' type in attributes, you must set data_type of kernel manually."
461 462 463
                attr_data_type_count = attr_data_type_count + 1

        # preprocess kernel configures
464
        kernel_select_code = self.gene_kernel_backend_select()
465 466 467 468

        if kernel['layout'] is not None:
            if '>' in kernel['layout']:
                vars_list = kernel['layout'].split('>')
469 470 471 472 473 474 475 476 477 478 479
                assert (
                    len(vars_list) == 2
                ), f"{api} api: The number of params to set layout with '>' only allows 2, but received {len(vars_list)}."
                assert (
                    vars_list[0].strip() in attrs['names']
                    and attrs['attr_info'][vars_list[0].strip()][0]
                    == 'DataLayout'
                ), f"{api} api: When use '>' to set kernel layout, the first param should be a attribute with DataLayout type."
                kernel_select_code = (
                    kernel_select_code
                    + f"""
480 481
  kernel_layout = ParseLayoutWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});
"""
482
                )
483 484 485

            else:
                vars_list = kernel['layout'].split(',')
486 487 488 489 490 491
                assert (
                    len(vars_list) == 1
                ), f"{api} api: The number of params to set layout must be 1, but received {len(vars_list)}."
                kernel_select_code = (
                    kernel_select_code
                    + f"""
492 493
  kernel_layout = ParseLayout({vars_list[0].strip()});
"""
494
                )
495 496

        if kernel['data_type'] is not None:
497 498 499 500 501 502 503 504 505 506 507

            def process_data_type_args(args_item):
                args_item = args_item.strip()
                complex_match_result = re.match(
                    r"complex\((?P<param_name>\w+)\)", args_item
                )
                if complex_match_result:
                    return f"phi::dtype::ToComplex(ParseDataType({complex_match_result.group('param_name')}))"
                else:
                    return f"ParseDataType({args_item})"

508 509
            if '>' in kernel['data_type']:
                vars_list = kernel['data_type'].split('>')
510 511 512 513 514 515 516 517 518 519 520
                assert (
                    len(vars_list) == 2
                ), f"{api} api: The number of params to set data_type with '>' only allows 2, but received {len(vars_list)}."
                assert (
                    vars_list[0].strip() in attrs['names']
                    and attrs['attr_info'][vars_list[0].strip()][0]
                    == 'DataType'
                ), f"{api} api: When use '>' to set kernel data_type, the first param should be a attribute with DataType type."
                kernel_select_code = (
                    kernel_select_code
                    + f"""
521 522
  kernel_data_type = ParseDataTypeWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});
"""
523
                )
524 525 526

            else:
                vars_list = kernel['data_type'].split(',')
527 528 529 530 531 532
                assert (
                    len(vars_list) == 1
                ), f"{api} api: The number of params to set data_type only allows 1, but received {len(vars_list)}."
                kernel_select_code = (
                    kernel_select_code
                    + f"""
533
  kernel_data_type = {process_data_type_args(vars_list[0])};
534
"""
535
                )
536 537

        if len(input_names) == 0:
538 539 540
            assert (
                attr_backend_count > 0 and attr_data_type_count > 0
            ), f"{api} api: When there is no input tensor, the args must have 'Place' and 'DataType'."
541 542 543 544 545 546 547 548 549 550 551

        kernel_select_args = ""
        for input_name in input_names:
            kernel_select_args = kernel_select_args + input_name + ", "

        if len(kernel_select_args) > 2:
            kernel_select_args = kernel_select_args[:-2]

        kernel_select_code = kernel_key_item_init + kernel_select_code

        if len(input_names) > 0:
552 553 554
            kernel_select_code = (
                kernel_select_code
                + f"""
555 556 557 558
  if (kernel_backend == Backend::UNDEFINED
        || kernel_layout == DataLayout::UNDEFINED
        || kernel_data_type == DataType::UNDEFINED ) {{
    auto kernel_key_set = ParseKernelKeyByInputArgs({kernel_select_args});
559
    auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();
560 561 562 563 564 565 566 567 568 569
    if (kernel_backend == Backend::UNDEFINED) {{
      kernel_backend = kernel_key.backend();
    }}
    if (kernel_layout == DataLayout::UNDEFINED) {{
      kernel_layout = kernel_key.layout();
    }}
    if (kernel_data_type == DataType::UNDEFINED) {{
      kernel_data_type = kernel_key.dtype();
    }}
  }}"""
570
            )
571 572 573

        return kernel_select_code

574
    def gene_infer_meta(self, kernel_output_names, code_indent) -> str:
575 576 577 578
        input_names = self.inputs['names']
        attr_names = self.attrs['names']
        infer_meta = self.infer_meta

579 580 581 582 583
        infer_meta_params = (
            infer_meta['param']
            if infer_meta['param'] is not None
            else input_names + attr_names
        )
584 585 586 587 588
        # generate meta tensors
        meta_tensor_code = ""
        param_code = ""
        for param in infer_meta_params:
            if param in input_names:
589
                if self.inputs['input_info'][param] == "const Tensor&":
590 591 592 593 594 595 596 597 598 599 600 601 602 603
                    param_code = (
                        param_code
                        + "MakeMetaTensor(*"
                        + PREFIX_TENSOR_NAME
                        + param
                        + "), "
                    )
                elif (
                    self.inputs['input_info'][param]
                    == "const std::vector<Tensor>&"
                ):
                    meta_tensor_code = (
                        meta_tensor_code
                        + f"""
604
{code_indent}  auto {param}_meta_vec = MakeMetaTensor({PREFIX_TENSOR_NAME}{param});
605
{code_indent}  std::vector<const phi::MetaTensor*> {param}_metas({param}_meta_vec.size());
606 607 608 609
{code_indent}  for (size_t i = 0; i < {param}_meta_vec.size(); ++i) {{
{code_indent}    {param}_metas[i] = &{param}_meta_vec[i];
{code_indent}  }}
"""
610
                    )
611
                    param_code = param_code + param + "_metas, "
612 613 614 615 616 617 618
                elif (
                    self.inputs['input_info'][param]
                    == "const paddle::optional<std::vector<Tensor>>&"
                ):
                    meta_tensor_code = (
                        meta_tensor_code
                        + f"""
619 620 621 622 623 624
{code_indent}  auto {param}_meta_vec = MakeMetaTensor({PREFIX_TENSOR_NAME}{param});
{code_indent}  paddle::optional<std::vector<const phi::MetaTensor*>> {param}_metas({param}_meta_vec.size());
{code_indent}  for (size_t i = 0; i < {param}_meta_vec.size(); ++i) {{
{code_indent}    {param}_metas->at(i) = &{param}_meta_vec[i];
{code_indent}  }}
"""
625
                    )
626 627
                    param_code = param_code + param + "_metas, "
                elif param in self.optional_vars:
628 629 630 631 632 633 634
                    param_code = (
                        param_code
                        + "MakeMetaTensor("
                        + PREFIX_TENSOR_NAME
                        + param
                        + "), "
                    )
635
                else:
636 637 638
                    raise ValueError(
                        f"{self.api} : Param of infer_meta error : {self.inputs['input_info'][param]} type is not supported."
                    )
639 640 641 642 643 644 645 646 647
            elif param in attr_names:
                param_code = param_code + param + ", "
            elif isinstance(param, str):
                param_code = param_code + "\"" + param + "\", "
            elif isinstance(param, bool):
                param_code = param_code + str(param).lower() + ", "
            else:
                param_code = param_code + str(param) + ", "

648 649
        for i, out_name in enumerate(kernel_output_names):
            if self.outputs['types'][i] == 'std::vector<Tensor>':
650 651 652
                meta_tensor_code = (
                    meta_tensor_code
                    + f"""
653 654 655
{code_indent}  auto {out_name}_{PREFIX_META_TENSOR_NAME}vec = MakeMetaTensor({out_name});
{code_indent}  std::vector<phi::MetaTensor*> {out_name}_metas({out_name}_{PREFIX_META_TENSOR_NAME}vec.size());
{code_indent}  for (size_t i = 0; i < {out_name}_{PREFIX_META_TENSOR_NAME}vec.size(); ++i) {{
656
{code_indent}    {out_name}_metas[i] = {out_name}[i] ? &{out_name}_{PREFIX_META_TENSOR_NAME}vec[i] : nullptr;
657
{code_indent}  }}"""
658
                )
659 660 661

                param_code = param_code + out_name + '_metas, '
            else:
662 663 664 665 666 667 668 669 670
                meta_tensor_code = (
                    meta_tensor_code
                    + code_indent
                    + "  phi::MetaTensor "
                    + out_name.replace('kernel_', PREFIX_META_TENSOR_NAME)
                    + "("
                    + out_name
                    + ");\n"
                )
671
                if len(kernel_output_names) == 1:
672 673 674 675
                    param_code = (
                        param_code
                        + f"&{out_name.replace('kernel_', PREFIX_META_TENSOR_NAME)}, "
                    )
676
                else:
677 678 679 680
                    param_code = (
                        param_code
                        + f"{out_name} ? &{out_name.replace('kernel_', PREFIX_META_TENSOR_NAME)} : nullptr, "
                    )
681

682 683
        param_code = param_code[:-2]
        return f"""{meta_tensor_code}
684
{code_indent}  phi::{infer_meta['func']}({param_code});
685 686
"""

Y
YuanRisheng 已提交
687 688 689 690 691 692 693 694
    def gene_trans_flag(self, input_name):
        trans_flag = "{}"
        if input_name in self.data_transform['skip_transform']:
            trans_flag = "{true}"
        elif input_name in self.data_transform['support_trans_dtype']:
            trans_flag = "{false, true}"
        return trans_flag

695 696 697
    def gene_dense_input(
        self, input_name, input_name_tensor_map, code_indent=''
    ):
Y
YuanRisheng 已提交
698 699
        input_tensor_code = ""
        trans_flag = self.gene_trans_flag(input_name)
700
        input_names = self.inputs['names']
Y
YuanRisheng 已提交
701 702 703 704 705 706
        attr_names = self.attrs['names']
        kernel_param = self.kernel['param']
        if kernel_param is None:
            kernel_param = input_names + attr_names

        input_name_tensor_map[input_name].append(
707 708 709 710 711
            (f"{PREFIX_TENSOR_NAME}{input_name}", False)
        )
        input_tensor_code = (
            input_tensor_code
            + f"""
712
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name} = PrepareData({input_name}, GetKernelInputArgDef(kernel.InputAt({kernel_param.index(input_name)}), kernel_backend), {trans_flag});"""
713
        )
Y
YuanRisheng 已提交
714
        return input_tensor_code
715

716 717 718
    def gene_selected_rows_input(
        self, input_name, input_name_tensor_map, code_indent=''
    ):
Y
YuanRisheng 已提交
719 720 721
        input_tensor_code = ""
        trans_flag = self.gene_trans_flag(input_name)
        input_names = self.inputs['names']
722 723 724 725 726
        attr_names = self.attrs['names']
        kernel_param = self.kernel['param']
        if kernel_param is None:
            kernel_param = input_names + attr_names

Y
YuanRisheng 已提交
727
        input_name_tensor_map[input_name].append(
728 729 730 731 732
            (f"{PREFIX_TENSOR_NAME}{input_name}", False)
        )
        input_tensor_code = (
            input_tensor_code
            + f"""
733
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name} = PrepareDataForSelectedRows({input_name}, GetKernelInputArgDef(kernel.InputAt({kernel_param.index(input_name)}), kernel_backend), {trans_flag});
Y
YuanRisheng 已提交
734
"""
735
        )
Y
YuanRisheng 已提交
736 737
        return input_tensor_code

738 739 740
    def gene_optional_vec_dense_input(
        self, input_name, input_name_tensor_map, code_indent=''
    ):
741
        input_tensor_code = ""
Y
YuanRisheng 已提交
742 743 744 745 746 747 748 749
        trans_flag = self.gene_trans_flag(input_name)
        input_names = self.inputs['names']
        attr_names = self.attrs['names']
        kernel_param = self.kernel['param']
        if kernel_param is None:
            kernel_param = input_names + attr_names
        if input_name in self.inplace_map.values():
            input_name_tensor_map[input_name].append(
750 751 752 753 754
                (f"{PREFIX_TENSOR_NAME}{input_name}", True)
            )
            input_tensor_code = (
                input_tensor_code
                + f"""
755
{code_indent}  paddle::optional<std::vector<const phi::DenseTensor*>> {PREFIX_TENSOR_NAME}{input_name} = TensorToConstDenseTensorPtr({input_name});"""
756
            )
Y
YuanRisheng 已提交
757 758
        else:
            input_name_tensor_map[input_name].append(
759 760 761 762 763
                (f"{PREFIX_TENSOR_NAME}{input_name}_vec", True)
            )
            input_tensor_code = (
                input_tensor_code
                + f"""
764
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name}_vec = PrepareData({input_name}, GetKernelInputArgDef(kernel.InputAt({kernel_param.index(input_name)}), kernel_backend), {trans_flag});
765 766 767 768 769 770 771
{code_indent}  paddle::optional<std::vector<const phi::DenseTensor*>> {PREFIX_TENSOR_NAME}{input_name};
{code_indent}  if ({PREFIX_TENSOR_NAME}{input_name}_vec){{
{code_indent}    {PREFIX_TENSOR_NAME}{input_name} = paddle::optional<std::vector<const phi::DenseTensor*>>({PREFIX_TENSOR_NAME}{input_name}_vec->size());
{code_indent}    for (size_t i = 0; i < {PREFIX_TENSOR_NAME}{input_name}_vec->size(); ++i) {{
{code_indent}      {PREFIX_TENSOR_NAME}{input_name}->at(i) = &{PREFIX_TENSOR_NAME}{input_name}_vec->at(i);
{code_indent}    }}
{code_indent}  }}"""
772
            )
Y
YuanRisheng 已提交
773
        return input_tensor_code
774

775 776 777
    def gene_vec_dense_input(
        self, input_name, input_name_tensor_map, code_indent=''
    ):
Y
YuanRisheng 已提交
778 779 780 781 782 783 784
        input_tensor_code = ""
        trans_flag = self.gene_trans_flag(input_name)
        input_names = self.inputs['names']
        attr_names = self.attrs['names']
        kernel_param = self.kernel['param']
        if kernel_param is None:
            kernel_param = input_names + attr_names
785

Y
YuanRisheng 已提交
786 787
        if input_name in self.inplace_map.values():
            input_name_tensor_map[input_name].append(
788 789 790 791 792
                (f"{PREFIX_TENSOR_NAME}{input_name}", True)
            )
            input_tensor_code = (
                input_tensor_code
                + f"""
793
{code_indent}  std::vector<const phi::DenseTensor*> {PREFIX_TENSOR_NAME}{input_name} = TensorToConstDenseTensorPtr({input_name});"""
794
            )
Y
YuanRisheng 已提交
795 796
        else:
            input_name_tensor_map[input_name].append(
797 798 799 800 801
                (f"{PREFIX_TENSOR_NAME}{input_name}_vec", True)
            )
            input_tensor_code = (
                input_tensor_code
                + f"""
802
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name}_vec = PrepareData({input_name}, GetKernelInputArgDef(kernel.InputAt({kernel_param.index(input_name)}), kernel_backend), {trans_flag});
803 804 805 806
{code_indent}  std::vector<const phi::DenseTensor*> {PREFIX_TENSOR_NAME}{input_name}({PREFIX_TENSOR_NAME}{input_name}_vec->size());
{code_indent}  for (size_t i = 0; i < {PREFIX_TENSOR_NAME}{input_name}.size(); ++i) {{
{code_indent}    {PREFIX_TENSOR_NAME}{input_name}[i] = &{PREFIX_TENSOR_NAME}{input_name}_vec->at(i);
{code_indent}  }}"""
807
            )
Y
YuanRisheng 已提交
808
        return input_tensor_code
809

Y
YuanRisheng 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822
    def gene_input(self, kernel_tensor_type=None, code_indent=''):
        input_names = self.inputs['names']
        attr_names = self.attrs['names']
        kernel_param = self.kernel['param']
        if kernel_param is None:
            kernel_param = input_names + attr_names
        input_name_tensor_map = collections.defaultdict(list)
        input_tensor_code = ""
        for i, input_name in enumerate(input_names):
            # set input code
            if input_name in kernel_param:
                # input is dense tensor
                api_tensor_type = self.inputs['input_info'][input_name]
823 824 825 826 827
                phi_tensor_type = (
                    'dense'
                    if kernel_tensor_type is None
                    else kernel_tensor_type[0][kernel_param.index(input_name)]
                )
Y
YuanRisheng 已提交
828 829
                if api_tensor_type in self.gene_input_func.keys():
                    input_tensor_code += self.gene_input_func[api_tensor_type][
830 831
                        phi_tensor_type
                    ](input_name, input_name_tensor_map, code_indent)
Y
YuanRisheng 已提交
832 833 834
                else:
                    # do nothing
                    pass
835 836 837
            else:
                if input_name in self.infer_meta['param']:
                    if input_name in self.optional_vars:
838 839 840
                        input_tensor_code = (
                            input_tensor_code
                            + f"""
841
{code_indent}  paddle::optional<phi::TensorBase> {PREFIX_TENSOR_NAME}{input_name} = {input_name} ? paddle::optional<phi::TensorBase>(*{input_name}->impl()) : paddle::none;"""
842
                        )
843

844
                    else:
845 846 847 848 849 850 851
                        if (
                            self.inputs['input_info'][input_name]
                            == "const std::vector<Tensor>&"
                        ):
                            input_tensor_code = (
                                input_tensor_code
                                + f"""
852 853
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name}_uq_ptr = TensorToDenseTensor({input_name});
{code_indent}  const auto& {PREFIX_TENSOR_NAME}{input_name} = *{PREFIX_TENSOR_NAME}{input_name}_uq_ptr;"""
854
                            )
855
                        else:
856 857 858
                            input_tensor_code = (
                                input_tensor_code
                                + f"""
859
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name} = {input_name}.impl();"""
860
                            )
Y
YuanRisheng 已提交
861 862 863 864 865

        return input_name_tensor_map, input_tensor_code

    def get_kernel_args(self, kernel_tensor_type=None, code_indent=''):
        dense_input_trans_map = {
866 867 868 869 870
            'const Tensor&': 'const phi::DenseTensor&',
            'const std::vector<Tensor>&': 'const std::vector<const phi::DenseTensor*>&',
            'const paddle::optional<Tensor&>': 'paddle::optional<const phi::DenseTensor&>',
            'const paddle::optional<Tensor>&': 'const paddle::optional<phi::DenseTensor>&',
            'const paddle::optional<std::vector<Tensor>>&': 'const paddle::optional<std::vector<const phi::DenseTensor*>>&',
Y
YuanRisheng 已提交
871 872 873
        }
        dense_out_trans_map = {
            'Tensor': 'phi::DenseTensor*',
874
            'std::vector<Tensor>': 'std::vector<phi::DenseTensor*>',
Y
YuanRisheng 已提交
875 876
        }
        sr_input_trans_map = {
877 878
            'const Tensor&': 'const phi::SelectedRows&',
            'const paddle::optional<Tensor>&': 'const paddle::optional<phi::SelectedRows>&',
Y
YuanRisheng 已提交
879 880 881 882
        }
        sr_out_trans_map = {'Tensor': 'phi::SelectedRows*'}
        input_names = self.inputs['names']
        input_infos = self.inputs['input_info']
883
        kernel_args_type_list = ['const phi::DeviceContext&']
Y
YuanRisheng 已提交
884 885 886 887 888 889 890

        attr_names = self.attrs['names']
        kernel_param = self.kernel['param']
        if kernel_param is None:
            kernel_param = input_names + attr_names

        input_name_tensor_map, input_tensor_code = self.gene_input(
891 892
            kernel_tensor_type, code_indent
        )
Y
YuanRisheng 已提交
893

894 895 896
        input_tensor_code = (
            input_tensor_code
            + f"""
897
{code_indent}  if(phi::RecordOpInfoSupplement::IsEnabled()){{"""
898
        )
899 900 901 902 903 904 905 906 907 908 909 910
        single_tensor_names = []
        list_tensor_names = []
        for input_name, input_tensors in input_name_tensor_map.items():
            has_vector_tensor = False
            for input_tensor, is_vector in input_tensors:
                if is_vector is True:
                    has_vector_tensor = True
            if has_vector_tensor is False:
                single_tensor_names.append(input_name)
            else:
                list_tensor_names.append(input_name)
        if not single_tensor_names:
911 912 913
            input_tensor_code = (
                input_tensor_code
                + f"""
914
{code_indent}     std::vector<std::pair<const char*, std::vector<phi::DDim>>> input_shapes;"""
915
            )
916
        else:
917 918 919
            for input_name in single_tensor_names:
                if input_name in self.optional_vars:
                    input_tensors = input_name_tensor_map[input_name]
920 921 922
                    input_tensor_code = (
                        input_tensor_code
                        + f"""
923
{code_indent}     std::vector<phi::DDim> {input_name}_record_shapes;"""
924
                    )
925
                    for input_tensor, _ in input_tensors:
926 927 928
                        input_tensor_code = (
                            input_tensor_code
                            + f"""
929 930 931
{code_indent}     if({input_tensor}){{
{code_indent}       {input_name}_record_shapes.push_back((*{input_tensor}).dims());
{code_indent}     }}"""
932
                        )
933

934 935 936
            input_tensor_code = (
                input_tensor_code
                + f"""
937
{code_indent}     std::vector<std::pair<const char*, std::vector<phi::DDim>>> input_shapes{{"""
938
            )
939
            for input_name in single_tensor_names[:-1]:
940
                if input_name in self.optional_vars:
941 942 943
                    input_tensor_code = (
                        input_tensor_code
                        + f"""
944
{code_indent}     {{"{input_name}", {input_name}_record_shapes}},"""
945
                    )
946
                else:
947 948 949
                    input_tensor_code = (
                        input_tensor_code
                        + f"""
950
{code_indent}     {{"{input_name}", {{"""
951
                    )
952 953
                    input_tensors = input_name_tensor_map[input_name]
                    for input_tensor, _ in input_tensors[:-1]:
954 955 956
                        input_tensor_code = (
                            input_tensor_code
                            + f"""
957
{code_indent}     (*{input_tensor}).dims(),"""
958 959 960 961
                        )
                    input_tensor_code = (
                        input_tensor_code
                        + f"""
962
{code_indent}     (*{input_tensors[-1][0]}).dims()}}}},"""
963
                    )
964
            if single_tensor_names[-1] in self.optional_vars:
965 966 967
                input_tensor_code = (
                    input_tensor_code
                    + f"""
968
{code_indent}     {{"{single_tensor_names[-1]}",
969
{code_indent}     {single_tensor_names[-1]}_record_shapes}}}};"""
970
                )
971
            else:
972 973 974
                input_tensor_code = (
                    input_tensor_code
                    + f"""
975
{code_indent}     {{"{single_tensor_names[-1]}", {{"""
976
                )
977 978
                input_tensors = input_name_tensor_map[single_tensor_names[-1]]
                for input_tensor, _ in input_tensors[:-1]:
979 980 981
                    input_tensor_code = (
                        input_tensor_code
                        + f"""
982
{code_indent}     (*{input_tensor}).dims(),"""
983 984 985 986
                    )
                input_tensor_code = (
                    input_tensor_code
                    + f"""
987
{code_indent}     (*{input_tensors[-1][0]}).dims()}}}}}};"""
988
                )
989
        if list_tensor_names:
990 991 992
            input_tensor_code = (
                input_tensor_code
                + f"""
993
{code_indent}     std::vector<phi::DDim> ddims_vec;"""
994
            )
995
        for input_name in list_tensor_names:
996 997 998
            input_tensor_code = (
                input_tensor_code
                + f"""
999
{code_indent}     ddims_vec.clear();"""
1000
            )
1001 1002
            for input_tensor, is_vector in input_name_tensor_map[input_name]:
                if is_vector:
1003 1004 1005 1006
                    input_tensor_truncate = input_tensor[:-4]
                    if input_name in self.inplace_map.values():
                        input_tensor_truncate = input_tensor

1007
                    if input_name in self.optional_vars:
1008 1009 1010
                        input_tensor_code = (
                            input_tensor_code
                            + f"""
1011 1012 1013 1014
{code_indent}     if ({input_tensor_truncate}){{
{code_indent}       ddims_vec.reserve({input_tensor_truncate}->size());
{code_indent}       for (size_t i = 0; i < {input_tensor_truncate}->size(); ++i) {{
{code_indent}         ddims_vec.emplace_back((*{input_tensor_truncate}->at(i)).dims());
1015 1016
{code_indent}       }}
{code_indent}     }}"""
1017
                        )
1018
                    else:
1019 1020 1021
                        input_tensor_code = (
                            input_tensor_code
                            + f"""
1022 1023 1024
{code_indent}     ddims_vec.reserve({input_tensor_truncate}.size());
{code_indent}     for (size_t i = 0; i < {input_tensor_truncate}.size(); ++i) {{
{code_indent}       ddims_vec.emplace_back((*{input_tensor_truncate}[i]).dims());
1025
{code_indent}     }}"""
1026
                        )
1027
                else:
1028 1029 1030
                    input_tensor_code = (
                        input_tensor_code
                        + f"""
1031 1032
                  ddims_vec.emplace_back((*{input_tensor}).dims());
{code_indent}     """
1033 1034 1035 1036
                    )
            input_tensor_code = (
                input_tensor_code
                + f"""
1037
{code_indent}     input_shapes.emplace_back("{input_name}", ddims_vec);"""
1038
            )
1039

1040
        input_tensor_code += f"""
1041
{code_indent}     phi::AttributeMap attrs;"""
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103

        for attr_name in self.attrs['names']:
            if 'IntArray' in self.attrs['attr_info'][attr_name][0]:
                input_tensor_code += f"""
{code_indent}     attrs["{attr_name}"] = {attr_name}.GetData();"""
            elif 'vector<phi::Scalar>' in self.attrs['attr_info'][attr_name][0]:
                input_tensor_code += f"""
{code_indent}     attrs["{attr_name}"] = "";"""  # TODO(kuizhiqing)
            elif 'Scalar' in self.attrs['attr_info'][attr_name][0]:
                input_tensor_code += f"""
{code_indent}    switch ({attr_name}.dtype()) {{
{code_indent}      case DataType::FLOAT32:
{code_indent}          attrs["{attr_name}"] = static_cast<float>({attr_name}.to<float>());
{code_indent}          break;
{code_indent}      case DataType::FLOAT64:
{code_indent}          attrs["{attr_name}"] = static_cast<double>({attr_name}.to<double>());
{code_indent}          break;
{code_indent}      case DataType::FLOAT16:
{code_indent}          attrs["{attr_name}"] = static_cast<float>({attr_name}.to<float16>());
{code_indent}          break;
{code_indent}      case DataType::BFLOAT16:
{code_indent}          attrs["{attr_name}"] = static_cast<float>({attr_name}.to<bfloat16>());
{code_indent}          break;
{code_indent}      case DataType::INT32:
{code_indent}          attrs["{attr_name}"] = static_cast<int32_t>({attr_name}.to<int32_t>());
{code_indent}          break;
{code_indent}      case DataType::INT64:
{code_indent}          attrs["{attr_name}"] = static_cast<int64_t>({attr_name}.to<int64_t>());
{code_indent}          break;
{code_indent}      case DataType::INT16:
{code_indent}          attrs["{attr_name}"] = static_cast<int16_t>({attr_name}.to<int16_t>());
{code_indent}          break;
{code_indent}      case DataType::INT8:
{code_indent}          attrs["{attr_name}"] = static_cast<int8_t>({attr_name}.to<int8_t>());
{code_indent}          break;
{code_indent}      case DataType::UINT16:
{code_indent}          attrs["{attr_name}"] = static_cast<uint16_t>({attr_name}.to<uint16_t>());
{code_indent}          break;
{code_indent}      case DataType::UINT8:
{code_indent}          attrs["{attr_name}"] = static_cast<uint8_t>({attr_name}.to<uint8_t>());
{code_indent}          break;
{code_indent}      case DataType::BOOL:
{code_indent}          attrs["{attr_name}"] = static_cast<bool>({attr_name}.to<bool>());
{code_indent}          break;
{code_indent}      case DataType::COMPLEX64:
{code_indent}          attrs["{attr_name}"] = static_cast<float>({attr_name}.to<complex64>());
{code_indent}          break;
{code_indent}      case DataType::COMPLEX128:
{code_indent}          attrs["{attr_name}"] = static_cast<double>({attr_name}.to<complex128>());
{code_indent}          break;
{code_indent}      default:
{code_indent}          attrs["{attr_name}"] = "";
{code_indent}          break;
{code_indent}    }}"""
            elif 'DataType' in self.attrs['attr_info'][attr_name][0]:
                pass  # no need
            elif 'Place' in self.attrs['attr_info'][attr_name][0]:
                pass  # no need
            else:
                input_tensor_code += f"""
{code_indent}     attrs["{attr_name}"] = {attr_name};"""

1104 1105 1106
        input_tensor_code = (
            input_tensor_code
            + f"""
1107
{code_indent}     phi::RecordOpInfoSupplement("{self.api}", input_shapes, attrs);
1108
{code_indent}  }}"""
1109
        )
1110
        kernel_args = ["*dev_ctx"]
1111 1112
        for param in kernel_param:
            if param in input_names:
1113
                if param in self.optional_vars:
1114
                    kernel_args.append(PREFIX_TENSOR_NAME + param)
1115
                else:
1116
                    if self.inputs['input_info'][param] == "const Tensor&":
1117
                        kernel_args.append("*" + PREFIX_TENSOR_NAME + param)
1118 1119 1120 1121
                    elif (
                        self.inputs['input_info'][param]
                        == "const std::vector<Tensor>&"
                    ):
1122
                        kernel_args.append(PREFIX_TENSOR_NAME + param)
1123 1124 1125
                    else:
                        # do nothing
                        pass
1126
                # input is dense tensor
1127 1128 1129 1130 1131
                if (
                    kernel_tensor_type is None
                    or kernel_tensor_type[0][kernel_param.index(param)]
                    == 'dense'
                ):
1132
                    kernel_args_type_list.append(
1133 1134
                        dense_input_trans_map[input_infos[param]]
                    )
1135 1136
                else:  # input is selected_rows
                    kernel_args_type_list.append(
1137 1138
                        sr_input_trans_map[input_infos[param]]
                    )
1139 1140
            elif param in attr_names:
                # set attr for kernel_context
1141 1142 1143
                if 'IntArray' in self.attrs['attr_info'][param][0]:
                    kernel_args_type_list.append('const phi::IntArray&')
                    param = 'phi::IntArray(' + param + ')'
1144 1145
                elif 'vector<phi::Scalar>' in self.attrs['attr_info'][param][0]:
                    kernel_args_type_list.append(
1146 1147
                        'const std::vector<phi::Scalar>&'
                    )
1148
                    param = param
1149
                elif 'Scalar' in self.attrs['attr_info'][param][0]:
1150 1151
                    kernel_args_type_list.append('const phi::Scalar&')
                    param = 'phi::Scalar(' + param + ')'
1152
                else:
1153
                    kernel_args_type_list.append(
1154 1155
                        self.attrs['attr_info'][param][0]
                    )
1156
                kernel_args.append(param)
1157
            elif isinstance(param, bool):
1158
                kernel_args.append(str(param).lower())
1159
            else:
1160
                kernel_args.append(str(param))
1161

1162 1163
        for i, out_type in enumerate(self.outputs['types']):
            # output is dense tensor
1164 1165 1166 1167
            if (
                kernel_tensor_type is None
                or kernel_tensor_type[1][i] == 'dense'
            ):
1168 1169 1170
                kernel_args_type_list.append(dense_out_trans_map[out_type])
            else:  # output is selected_rows
                kernel_args_type_list.append(sr_out_trans_map[out_type])
1171 1172 1173

        kernel_signature = "void(*)(" + ", ".join(kernel_args_type_list) + ")"

1174
        return input_tensor_code, ", ".join(kernel_args), kernel_signature
1175

1176 1177
    # Override by child class
    def gene_return_code(self):
1178
        return "return api_output;"
1179

1180
    # Override by child class
1181 1182 1183 1184 1185 1186 1187
    def gene_output(
        self,
        out_dtype_list,
        out_tensor_type_list=None,
        code_indent='',
        inplace_flag=False,
    ):
1188 1189
        return None, None, None

1190 1191 1192 1193 1194
    def reset_view_after_fallback(
        self, out_dtype_list, code_indent='', inplace_flag=False
    ):
        return ''

1195 1196
    def gen_kernel_code(self, kernel_name, code_indent, inplace_flag=False):
        kernel_dispatch = self.kernel['dispatch'][kernel_name]
1197
        input_tensors, kernel_args, kernel_signature = self.get_kernel_args(
1198 1199
            kernel_dispatch, code_indent
        )
1200
        out_tensor_type_list = kernel_dispatch[1] if kernel_dispatch else None
1201
        outputs_args, kernel_output_names, output_create = self.gene_output(
1202 1203 1204 1205 1206
            self.outputs['types'],
            out_tensor_type_list,
            code_indent,
            inplace_flag,
        )
1207 1208
        fallback_kernel_output_trans = ""
        for kernel_out in outputs_args:
1209
            fallback_kernel_output_trans += f"""
1210
{code_indent}    TransDataBackend({kernel_out}, kernel_backend, {kernel_out});"""
1211
        return f"""
F
From00 已提交
1212
{code_indent}  VLOG(6) << "{self.api} API kernel key: [" << kernel_backend << ", " << kernel_layout << ", "<< kernel_data_type << "]";
1213
{code_indent}  auto kernel_result = phi::KernelFactory::Instance().SelectKernelOrThrowError(
1214
{code_indent}      "{kernel_name}", {{kernel_backend, kernel_layout, kernel_data_type}});
1215
{code_indent}  const auto& kernel = kernel_result.kernel;
1216 1217 1218
{code_indent}  if (FLAGS_low_precision_op_list) {{
{code_indent}    phi::KernelFactory::Instance().AddToLowPrecisionKernelList("{self.api}", kernel_data_type);
{code_indent}  }}
1219
{code_indent}  VLOG(6) << "{kernel_name} kernel: " << kernel;
1220
{code_indent}  auto* dev_ctx = GetDeviceContextByBackend(kernel_result.has_fallback_cpu ? Backend::CPU : kernel_backend);
1221 1222
{input_tensors}
{output_create}
1223 1224 1225
{code_indent}  phi::RecordEvent *infer_shape_record_event = nullptr;
{code_indent}  if(phi::RecordEvent::IsEnabled()){{
{code_indent}    infer_shape_record_event = new phi::RecordEvent(\"{self.api} infer_meta\", phi::TracerEventType::OperatorInner, 1);
1226
{code_indent}  }}
1227
{self.gene_infer_meta(kernel_output_names, code_indent)}
1228 1229 1230
{code_indent}  if(infer_shape_record_event != nullptr){{
{code_indent}    delete infer_shape_record_event;
{code_indent}  }}
1231 1232
{code_indent}  using kernel_signature = {kernel_signature};
{code_indent}  auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
1233 1234 1235
{code_indent}  phi::RecordEvent* kernel_record_event = nullptr;
{code_indent}  if(phi::RecordEvent::IsEnabled()){{
{code_indent}    kernel_record_event = new phi::RecordEvent(\"{self.api} compute\", phi::TracerEventType::OperatorInner, 1);
1236
{code_indent}  }}
1237
{code_indent}    (*kernel_fn)({kernel_args}, {", ".join(outputs_args)});
1238 1239
{code_indent}  if(kernel_record_event != nullptr){{
{code_indent}    delete kernel_record_event;
1240 1241 1242
{code_indent}  }}
{code_indent}  if (kernel_result.has_fallback_cpu) {{
{fallback_kernel_output_trans}
1243
{self.reset_view_after_fallback(self.outputs['types'], code_indent, inplace_flag)}
1244
{code_indent}  }}
1245
{code_indent}  {self.gene_return_code()}"""
1246

1247
    def get_condition_code(self, kernel_name):
1248 1249 1250
        assert self.kernel['dispatch'][
            kernel_name
        ], f"{self.api} api: the tensor type of inputs and outputs for kernel isn't set, see also 'kernel:func' of 'scale' in ops.yaml."
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
        input_types = self.kernel['dispatch'][kernel_name][0]
        condition_list = []
        for i, in_type in enumerate(input_types):
            if in_type == "dense":
                if self.inputs['names'][i] in self.optional_vars:
                    condition_list.append(
                        f"(!{self.inputs['names'][i]} || {self.inputs['names'][i]}->is_dense_tensor())"
                    )
                else:
                    condition_list.append(
1261 1262
                        f"{self.inputs['names'][i]}.is_dense_tensor()"
                    )
1263 1264 1265 1266 1267 1268 1269
            else:
                if self.inputs['names'][i] in self.optional_vars:
                    condition_list.append(
                        f"(!{self.inputs['names'][i]} || {self.inputs['names'][i]}->is_selected_rows())"
                    )
                else:
                    condition_list.append(
1270 1271
                        f"{self.inputs['names'][i]}.is_selected_rows()"
                    )
1272
        return " && ".join(condition_list)
1273

1274 1275 1276 1277 1278 1279
    def gene_dispatch_code(self, kernel_name, inplace_flag=False):
        return f"""
  if ({self.get_condition_code(kernel_name)}) {{
{self.gen_kernel_code(kernel_name, '  ', inplace_flag)}
  }}
"""
1280

1281
    def gene_base_api_code(self, inplace_flag=False):
1282 1283 1284
        api_func_name = self.get_api_func_name()
        if inplace_flag and api_func_name[-1] != '_':
            api_func_name += '_'
1285
        api_code = f"""
1286
PADDLE_API {self.get_return_type(inplace_flag)} {api_func_name}({self.get_define_args(inplace_flag)}) {{
1287
{self.gene_kernel_select()}
1288
"""
1289

1290 1291 1292 1293
        if len(self.kernel['func']) > 1:
            kernel_dispatch_code = ''
            for kernel_name in self.kernel['func']:
                kernel_dispatch_code += self.gene_dispatch_code(
1294 1295 1296 1297 1298
                    kernel_name, inplace_flag
                )
            return (
                api_code
                + f"""
1299 1300 1301
{kernel_dispatch_code}
  PADDLE_THROW(phi::errors::Unimplemented(
          "The kernel of ({self.api}) for input tensors is unimplemented, please check the type of input tensors."));
1302
}}
1303
"""
1304
            )
1305
        else:
1306 1307 1308 1309
            return (
                api_code
                + self.gen_kernel_code(self.kernel['func'][0], '', inplace_flag)
                + """
1310
}
1311
"""
1312
            )
1313

1314 1315
    def gene_invoke_code(self, invoke_code, params_code):
        return f"""
1316
PADDLE_API {self.get_return_type()} {self.api}({params_code}) {{
1317 1318 1319
  return {invoke_code};
}}"""

1320 1321 1322
    def gene_api_code(self):
        if self.is_base_api:
            api_code = self.gene_base_api_code()
1323
            if len(self.inplace_map) > 0:
Z
zyfncg 已提交
1324 1325
                if self.api[-1] == '_':
                    api_code = ""
1326 1327
                api_code = api_code + self.gene_base_api_code(inplace_flag=True)
            return api_code
X
xiaoguoguo626807 已提交
1328 1329 1330
        elif self.is_only_composite_api:
            # for composite and invoke api, dygraph use prim::xxx_grad method
            return ''
1331
        else:
X
xiaoguoguo626807 已提交
1332 1333
            invoke_code = self.invoke
            params_code = self.get_define_args()
1334
            return self.gene_invoke_code(invoke_code, params_code)