api_base.py 39.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.

import re

17
PREFIX_TENSOR_NAME = 'input_'
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
PREFIX_META_TENSOR_NAME = 'meta_'


class BaseAPI(object):
    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
34
        #     out_size_expr : [], expression for getting size of vector<Tensor>
35
        self.inputs, self.attrs, self.outputs, self.optional_vars = self.parse_args(
36 37 38 39 40 41 42
            self.api, api_item_yaml)

        self.is_base_api = True
        if 'invoke' in api_item_yaml:
            self.is_base_api = False
            self.invoke = api_item_yaml['invoke']
        else:
43 44 45
            if 'infer_meta' in api_item_yaml:
                self.infer_meta = self.parse_infer_meta(api_item_yaml[
                    'infer_meta'])
46 47
            self.kernel = self.parse_kernel(api_item_yaml['kernel'])
            self.support_selected_rows_kernel = False if len(self.kernel[
48 49
                'func']) == 1 or not self.kernel['func'][1].endswith(
                    '_sr') else True
50
            self.data_transform = self.parse_data_transform(api_item_yaml)
51 52
            self.inplace_map, self.view_map = self.parse_inplace_and_view(
                api_item_yaml)
53 54 55 56

    def get_api_name(self, api_item_yaml):
        return api_item_yaml['api']

57 58 59
    def get_api_func_name(self):
        return self.api

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    def get_input_tensor_args(self, inplace_flag=False):
        input_args = []
        inplace_type_map = {
            "const Tensor&": "Tensor&",
            "const std::vector<Tensor>&": "std::vector<Tensor>&"
        }
        for name in self.inputs['names']:
            name = name.split('@')[0]
            if inplace_flag and name in self.inplace_map.values():
                input_args.append(inplace_type_map[self.inputs['input_info'][
                    name]] + ' ' + name)
            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]
            declare_args.append(self.attrs['attr_info'][name][0] + ' ' + name +
                                default_value)
83

84 85 86 87 88 89 90 91
        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)
92

93
    def parse_args(self, api_name, api_item_yaml):
94 95 96 97 98
        optional_vars = []
        if 'optional' in api_item_yaml:
            optional_vars = [
                item.strip() for item in api_item_yaml['optional'].split(',')
            ]
99
        inputs, attrs = self.parse_input_and_attr(
100
            api_name, api_item_yaml['args'], optional_vars)
101
        output_type_list, output_names, out_size_expr = self.parse_output(
102 103 104 105
            api_name, api_item_yaml['output'])
        return inputs, attrs, {
            'names': output_names,
            'types': output_type_list,
106 107
            'out_size_expr': out_size_expr
        }, optional_vars
108

109
    def parse_input_and_attr(self, api_name, args_config, optional_vars=[]):
110 111 112 113 114 115 116
        inputs = {'names': [], 'input_info': {}}
        attrs = {'names': [], 'attr_info': {}}
        args_str = args_config.strip()
        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."
        args_str = args_str[1:-1]
        args_list = args_str.split(',')
Z
zyfncg 已提交
117 118 119 120
        input_types_map = {
            'Tensor': 'const Tensor&',
            'Tensor[]': 'const std::vector<Tensor>&'
        }
121
        attr_types_map = {
122
            'IntArray': 'const IntArray&',
123
            'Scalar': 'const Scalar&',
124 125 126 127
            'Scalar(int)': 'const Scalar&',
            'Scalar(int64_t)': 'const Scalar&',
            'Scalar(float)': 'const Scalar&',
            'Scalar(dobule)': 'const Scalar&',
128
            'int': 'int',
129 130
            'int32_t': 'int32_t',
            'int64_t': 'int64_t',
131 132 133 134 135
            'long': 'long',
            'size_t': 'size_t',
            'float': 'float',
            'double': 'double',
            'bool': 'bool',
136
            'str': 'const std::string&',
137
            'Place': 'const Place&',
138 139
            'DataLayout': 'DataLayout',
            'DataType': 'DataType',
140 141
            'int64_t[]': 'const std::vector<int64_t>&',
            'int[]': 'const std::vector<int>&'
142 143
        }
        optional_types_trans = {
H
hong 已提交
144
            'Tensor': 'paddle::optional<const Tensor&>',
145 146
            'Tensor[]': 'const paddle::optional<std::vector<Tensor>>&',
            'int': 'paddle::optional<int>',
147 148
            'int32_t': 'paddle::optional<int32_t>',
            'int64_t': 'paddle::optional<int64_t>',
149 150 151
            'float': 'paddle::optional<float>',
            'double': 'paddle::optional<double>',
            'bool': 'paddle::optional<bool>',
152
            'Place': 'paddle::optional<const Place&>',
153
            'DataLayout': 'paddle::optional<DataLayout>',
154
            'DataType': 'paddle::optional<DataType>'
155 156
        }

157 158
        for item in args_list:
            item = item.strip()
Z
zyfncg 已提交
159
            type_and_name = item.split(' ')
160 161
            # match the input tensor
            has_input = False
Z
zyfncg 已提交
162 163 164
            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()
165 166 167 168 169
                    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"

170 171 172
                    if input_name in optional_vars:
                        in_type = optional_types_trans[in_type_symbol]

173 174 175 176 177 178 179 180
                    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 已提交
181 182 183
            for attr_type_symbol, attr_type in attr_types_map.items():
                if type_and_name[0] == attr_type_symbol:
                    attr_name = item[len(attr_type_symbol):].strip()
184 185 186 187 188 189 190 191
                    assert len(attr_name) > 0, \
                        f"The attribute name should not be empty. Please check the args of {api_name} in yaml."
                    default_value = None
                    if '=' in attr_name:
                        attr_infos = attr_name.split('=')
                        attr_name = attr_infos[0].strip()
                        default_value = attr_infos[1].strip()

192 193 194
                    if attr_name in optional_vars:
                        attr_type = optional_types_trans[attr_type_symbol]

195 196 197 198 199
                    default_value_str = "" if default_value is None else '=' + default_value
                    attrs['names'].append(attr_name)
                    attrs['attr_info'][attr_name] = (attr_type, default_value)
                    break

200
        return inputs, attrs
201 202 203

    def parse_output(self, api_name, output_config):
        def parse_output_item(output_item):
Z
zyfncg 已提交
204 205 206 207
            output_type_map = {
                'Tensor': 'Tensor',
                'Tensor[]': 'std::vector<Tensor>'
            }
208 209 210 211 212 213 214 215 216 217 218 219 220 221
            result = re.search(
                r"(?P<out_type>[a-zA-Z0-9_[\]]+)\s*(?P<name>\([a-zA-Z0-9_@]+\))?\s*(?P<expr>\{[^\}]+\})?",
                output_item)
            assert result is not None, f"{api_name} : the output config parse error."
            out_type = result.group('out_type')
            assert out_type in output_type_map, \
                f"{api_name} : Output type error: the output type only support Tensor and Tensor[], \
                  but now is {out_type}."

            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]
            return output_type_map[out_type], out_name, out_size_expr
222 223 224 225

        temp_list = output_config.split(',')

        if len(temp_list) == 1:
226
            out_type, out_name, size_expr = parse_output_item(temp_list[0])
227
            return [out_type], [out_name], size_expr
228 229 230 231
        else:
            out_type_list = []
            out_name_list = []
            for output_item in temp_list:
232
                out_type, out_name, size_expr = parse_output_item(output_item)
233 234 235
                out_type_list.append(out_type)
                out_name_list.append(out_name)

236
            return out_type_list, out_name_list, size_expr
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251
    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
252
        #    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)})
253 254 255 256 257
        kernel = {
            'func': [],
            'param': None,
            'backend': None,
            'layout': None,
Z
zyfncg 已提交
258
            'data_type': None,
259 260
            'use_gpudnn': 'false',
            'dispatch': {}
261 262 263 264 265 266 267 268 269
        }
        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']
270 271 272 273
        if 'use_gpudnn' in kernel_config:
            kernel['use_gpudnn'] = kernel_config['use_gpudnn']
            if isinstance(kernel['use_gpudnn'], bool):
                kernel['use_gpudnn'] = str(kernel['use_gpudnn']).lower()
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        kernel_funcs = re.compile(r'([a-zA-Z0-9_]+)\s*({[^}]+})?').findall(
            kernel_config['func'])

        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(',')]
            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(
                func_item[1])
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

        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[
                    'data_transform']['skip_transform']
            if 'support_trans_dtype' in api_item_yaml['data_transform']:
                data_transform['support_trans_dtype'] = api_item_yaml[
                    'data_transform']['support_trans_dtype']

        return data_transform

304
    def parse_inplace_and_view(self, api_item_yaml):
305
        inplace_map, view_map = {}, {}
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        for mode in ['inplace', 'view']:
            if mode in api_item_yaml:
                if mode == 'inplace':
                    inplace_map = {}
                else:
                    view_map = {}
                in_out_mapping_list = api_item_yaml[mode].split(',')
                for item in in_out_mapping_list:
                    result = re.search(r"(?P<in>\w+)\s*->\s(?P<out>\w+)", item)
                    in_val = result.group('in')
                    out_val = result.group('out')
                    assert in_val in self.inputs['names'], \
                        f"{self.api} : {mode} input error: the input var name('{in_val}') is not found in the input args of {self.api}."
                    assert out_val in self.outputs['names'], \
                        f"{self.api} : {mode} output error: the output var name('{out_val}') is not found in the output args of {self.api}."

                    if mode == 'inplace':
                        inplace_map[out_val] = in_val
                    else:
                        view_map[out_val] = in_val

        return inplace_map, view_map
328

329
    # Override by child class
330
    def get_return_type(self, inplace_flag=False):
331 332 333
        return None

    def gene_api_declaration(self):
334 335 336 337 338
        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()});
339 340
"""

341 342 343
        if self.is_base_api and len(self.inplace_map) > 0:
            if api_func_name[-1] != '_':
                api_func_name += '_'
344
            api_declaration = api_declaration + f"""
345
PADDLE_API {self.get_return_type(inplace_flag=True)} {api_func_name}({self.get_declare_args(inplace_flag=True)});
346 347 348 349
"""

        return api_declaration

350 351 352 353 354 355 356 357 358
    # 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('>')
                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)}."
359
                assert (vars_list[0].strip() in self.attrs['names']) and (self.attrs['attr_info'][vars_list[0].strip()][0] == 'const Place&'), \
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
                    f"{self.api} api: When use '>' to set kernel backend, the first param should be a attribute with Place type."
                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

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    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']:
391
            if attrs['attr_info'][attr_name][0] == 'const Place&':
392
                assert kernel['backend'] is not None, \
393
                    f"{api} api: When there is a parameter with 'Place' type in attributes, you must set backend of kernel manually."
394 395 396 397 398 399 400 401 402 403 404
                attr_backend_count = attr_backend_count + 1
            if attrs['attr_info'][attr_name][0] == 'DataLayout':
                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."
                attr_layout_count = attr_layout_count + 1
            if attrs['attr_info'][attr_name][0] == 'DataType':
                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."
                attr_data_type_count = attr_data_type_count + 1

        # preprocess kernel configures
405
        kernel_select_code = self.gene_kernel_backend_select()
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

        if kernel['layout'] is not None:
            if '>' in kernel['layout']:
                vars_list = kernel['layout'].split('>')
                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"""
  kernel_layout = ParseLayoutWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});
"""

            else:
                vars_list = kernel['layout'].split(',')
                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"""
  kernel_layout = ParseLayout({vars_list[0].strip()});
"""

        if kernel['data_type'] is not None:
            if '>' in kernel['data_type']:
                vars_list = kernel['data_type'].split('>')
                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"""
  kernel_data_type = ParseDataTypeWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});
"""

            else:
                vars_list = kernel['data_type'].split(',')
                assert len(
                    vars_list
444
                ) == 1, f"{api} api: The number of params to set data_type only allows 1, but received {len(vars_list)}."
445 446 447 448 449
                kernel_select_code = kernel_select_code + f"""
  kernel_data_type = ParseDataType({vars_list[0].strip()});
"""

        if len(input_names) == 0:
450
            assert attr_backend_count > 0 and attr_data_type_count > 0, \
451
                f"{api} api: When there is no input tensor, the args must have 'Place' and 'DataType'."
452 453 454 455 456 457 458 459 460 461 462

        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:
463 464
            if self.support_selected_rows_kernel:
                kernel_select_code = kernel_select_code + f"""
465
  KernelType kernel_type = ParseKernelTypeByInputArgs({", ".join(input_names)});
466 467
"""

468 469 470 471 472
            kernel_select_code = kernel_select_code + f"""
  if (kernel_backend == Backend::UNDEFINED
        || kernel_layout == DataLayout::UNDEFINED
        || kernel_data_type == DataType::UNDEFINED ) {{
    auto kernel_key_set = ParseKernelKeyByInputArgs({kernel_select_args});
473
    auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();
474 475 476 477 478 479 480 481 482 483 484 485 486
    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();
    }}
  }}"""

        return kernel_select_code

487
    def gene_infer_meta(self, kernel_output_names, code_indent) -> str:
488 489 490 491
        input_names = self.inputs['names']
        attr_names = self.attrs['names']
        infer_meta = self.infer_meta

492 493
        infer_meta_params = infer_meta['param'] if infer_meta[
            'param'] is not None else input_names + attr_names
494 495 496 497 498
        # generate meta tensors
        meta_tensor_code = ""
        param_code = ""
        for param in infer_meta_params:
            if param in input_names:
499 500 501 502 503
                if self.inputs['input_info'][param] == "const Tensor&":
                    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"""
504
{code_indent}  auto {param}_meta_vec = MakeMetaTensor({PREFIX_TENSOR_NAME}{param});
505
{code_indent}  std::vector<const phi::MetaTensor*> {param}_metas({param}_meta_vec.size());
506 507 508 509 510 511 512
{code_indent}  for (size_t i = 0; i < {param}_meta_vec.size(); ++i) {{
{code_indent}    {param}_metas[i] = &{param}_meta_vec[i];
{code_indent}  }}
"""

                    param_code = param_code + param + "_metas, "
                elif param in self.optional_vars:
513
                    meta_tensor_code = meta_tensor_code + f"""
H
hong 已提交
514
{code_indent}  paddle::optional<const phi::MetaTensor&> {PREFIX_TENSOR_NAME}meta_ref_{param} = paddle::none;
515 516
{code_indent}  phi::DenseTensor {param}_dt;
{code_indent}  phi::MetaTensor {PREFIX_TENSOR_NAME}meta_tmp_{param}({param}_dt);
H
hong 已提交
517 518 519 520 521 522
{code_indent}  if ({PREFIX_TENSOR_NAME}{param}_ptr) {{
{code_indent}    {PREFIX_TENSOR_NAME}meta_tmp_{param}.set_dtype( {PREFIX_TENSOR_NAME}{param}_ptr->dtype() );
{code_indent}    {PREFIX_TENSOR_NAME}meta_tmp_{param}.set_dims( {PREFIX_TENSOR_NAME}{param}_ptr->dims() );
{code_indent}    {PREFIX_TENSOR_NAME}meta_tmp_{param}.set_layout( {PREFIX_TENSOR_NAME}{param}_ptr->layout() );
{code_indent}    {PREFIX_TENSOR_NAME}meta_ref_{param} =  {PREFIX_TENSOR_NAME}meta_tmp_{param};
{code_indent}  }}\n"""
523 524 525

                    param_code = param_code + f"{PREFIX_TENSOR_NAME}meta_ref_{param}, "
                else:
526 527 528
                    raise ValueError(
                        f"{self.api} : Param of infer_meta error : {self.inputs['input_info'][param]} type is not supported."
                    )
529 530 531 532 533 534 535 536 537
            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) + ", "

538 539 540 541 542 543
        for i, out_name in enumerate(kernel_output_names):
            if self.outputs['types'][i] == 'std::vector<Tensor>':
                meta_tensor_code = meta_tensor_code + f"""
{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) {{
544
{code_indent}    {out_name}_metas[i] = {out_name}[i] ? &{out_name}_{PREFIX_META_TENSOR_NAME}vec[i] : nullptr;
545 546 547 548 549 550 551
{code_indent}  }}"""

                param_code = param_code + out_name + '_metas, '
            else:
                meta_tensor_code = meta_tensor_code + code_indent + "  phi::MetaTensor " + out_name.replace(
                    'kernel_',
                    PREFIX_META_TENSOR_NAME) + "(" + out_name + ");\n"
552 553 554 555
                if len(kernel_output_names) == 1:
                    param_code = param_code + f"&{out_name.replace('kernel_', PREFIX_META_TENSOR_NAME)}, "
                else:
                    param_code = param_code + f"{out_name} ? &{out_name.replace('kernel_', PREFIX_META_TENSOR_NAME)} : nullptr, "
556

557 558
        param_code = param_code[:-2]
        return f"""{meta_tensor_code}
559
{code_indent}  phi::{infer_meta['func']}({param_code});
560 561
"""

562
    def get_kernel_args(self, code_indent):
563
        input_trans_map = {
564
            'const Tensor&': 'const phi::DenseTensor&',
565
            'const std::vector<Tensor>&':
566
            'const std::vector<const phi::DenseTensor*>&',
H
hong 已提交
567 568 569
            'const paddle::optional<Tensor&>':
            'paddle::optional<const phi::DenseTensor&>',
            'paddle::optional<const Tensor&>':
570 571 572
            'paddle::optional<const phi::DenseTensor&>',
            'const paddle::optional<std::vector<Tensor>>&':
            'paddle::optional<const std::vector<phi::DenseTensor>&>'
573 574
        }
        out_trans_map = {
575 576
            'Tensor': 'phi::DenseTensor*',
            'std::vector<Tensor>': 'std::vector<phi::DenseTensor*>&'
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        }
        input_names = self.inputs['names']
        input_infos = self.inputs['input_info']
        kernel_args_type_list = ['const platform::DeviceContext&']

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

        input_tensor_code = ""
        for i, input_name in enumerate(input_names):
            # set input code
            if input_name in kernel_param:
                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}"
596 597 598 599 600 601 602 603 604
                if input_name in self.optional_vars:
                    input_tensor_code = input_tensor_code + f"""
{code_indent}  {input_trans_map[input_infos[input_name]]} {PREFIX_TENSOR_NAME}{input_name}(paddle::none);
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name}_ptr = PrepareData({input_name}, kernel.InputAt({i}), {trans_flag});
{code_indent}  if ({PREFIX_TENSOR_NAME}{input_name}_ptr) {{
{code_indent}    {PREFIX_TENSOR_NAME}{input_name} = paddle::make_optional<const phi::DenseTensor&>(*{PREFIX_TENSOR_NAME}{input_name}_ptr);
{code_indent}  }}"""

                else:
605 606
                    if self.inputs['input_info'][input_name] == "const Tensor&":
                        input_tensor_code = input_tensor_code + f"""
607
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name} = PrepareData({input_name}, kernel.InputAt({i}), {trans_flag});"""
608

609 610 611 612 613 614 615 616 617 618 619 620
                    elif self.inputs['input_info'][
                            input_name] == "const std::vector<Tensor>&":
                        input_tensor_code = input_tensor_code + f"""
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name}_vec = PrepareData({input_name}, kernel.InputAt({i}), {trans_flag});
{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}  }}"""

                    else:
                        # do nothing
                        pass
621
            else:
622 623 624 625 626 627 628 629 630 631
                if input_name in self.optional_vars:
                    input_tensor_code = input_tensor_code + f"""
{code_indent}  {input_trans_map[input_infos[input_name]]} {PREFIX_TENSOR_NAME}{input_name}(paddle::none);
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name}_ptr = TensorToDenseTensor({input_name});
{code_indent}  if ({PREFIX_TENSOR_NAME}{input_name}_ptr) {{
{code_indent}    {PREFIX_TENSOR_NAME}{input_name} = paddle::make_optional<const phi::DenseTensor&>(*{PREFIX_TENSOR_NAME}{input_name}_ptr);
{code_indent}  }}"""

                else:
                    input_tensor_code = input_tensor_code + f"""
632 633 634 635 636
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name} = TensorToDenseTensor({input_name});"""

        kernel_args = "*dev_ctx, "
        for param in kernel_param:
            if param in input_names:
637 638 639
                if param in self.optional_vars:
                    kernel_args = kernel_args + PREFIX_TENSOR_NAME + param + ", "
                else:
640 641 642
                    if self.inputs['input_info'][param] == "const Tensor&":
                        kernel_args = kernel_args + "*" + PREFIX_TENSOR_NAME + param + ", "
                    elif self.inputs['input_info'][
643
                            param] == "const std::vector<Tensor>&":
644 645 646 647
                        kernel_args = kernel_args + PREFIX_TENSOR_NAME + param + ", "
                    else:
                        # do nothing
                        pass
648 649
                kernel_in_type = input_trans_map[input_infos[param]]
                kernel_args_type_list.append(kernel_in_type)
650 651
            elif param in attr_names:
                # set attr for kernel_context
652 653 654
                if 'IntArray' in self.attrs['attr_info'][param][0]:
                    kernel_args_type_list.append('const phi::IntArray&')
                    param = 'phi::IntArray(' + param + ')'
655
                elif 'Scalar' in self.attrs['attr_info'][param][0]:
656 657
                    kernel_args_type_list.append('const phi::Scalar&')
                    param = 'phi::Scalar(' + param + ')'
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
                else:
                    kernel_args_type_list.append(self.attrs['attr_info'][param][
                        0])
                kernel_args = kernel_args + param + ", "
            elif isinstance(param, bool):
                kernel_args = kernel_args + str(param).lower() + ", "
            else:
                kernel_args = kernel_args + str(param) + ", "

        for out_type in self.outputs['types']:
            kernel_args_type_list.append(out_trans_map[out_type])

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

        return input_tensor_code, kernel_args[:-2], kernel_signature

    def get_selected_rows_kernel_args(self, code_indent):
        input_trans_map = {
676
            'const Tensor&': 'const phi::SelectedRows&',
677 678
            'const paddle::optional<Tensor>&':
            'paddle::optional<const phi::SelectedRows&>'
679
        }
680
        out_trans_map = {'Tensor': 'phi::SelectedRows*'}
681 682 683 684 685 686 687 688 689 690 691 692
        input_names = self.inputs['names']
        input_infos = self.inputs['input_info']
        kernel_args_type_list = ['const platform::DeviceContext&']

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

        input_tensor_code = ""
        for i, input_name in enumerate(input_names):
            # set input code
693 694 695 696 697 698 699 700 701 702 703
            if input_name in self.optional_vars:
                input_tensor_code = input_tensor_code + f"""

{code_indent}  {input_trans_map[input_infos[input_name]]} {PREFIX_TENSOR_NAME}{input_name}(paddle::none);
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name}_ptr = TensorToSelectedRows({input_name});
{code_indent}  if ({PREFIX_TENSOR_NAME}{input_name}_ptr) {{
{code_indent}    {PREFIX_TENSOR_NAME}{input_name} = paddle::make_optional<const phi::SelectedRows&>(*{PREFIX_TENSOR_NAME}{input_name}_ptr);
{code_indent}  }}"""

            else:
                input_tensor_code = input_tensor_code + f"""
704
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name} = TensorToSelectedRows({input_name});"""
705 706 707 708

        kernel_args = "*dev_ctx, "
        for param in kernel_param:
            if param in input_names:
709 710 711 712 713 714
                if param in self.optional_vars:
                    kernel_args = kernel_args + PREFIX_TENSOR_NAME + param + ", "
                else:
                    kernel_args = kernel_args + "*" + PREFIX_TENSOR_NAME + param + ", "
                kernel_in_type = input_trans_map[input_infos[param]]
                kernel_args_type_list.append(kernel_in_type)
715 716
            elif param in attr_names:
                # set attr for kernel_context
717 718 719
                if 'IntArray' in self.attrs['attr_info'][param][0]:
                    kernel_args_type_list.append('const phi::IntArray&')
                    param = 'phi::IntArray(' + param + ')'
720
                elif 'Scalar' in self.attrs['attr_info'][param][0]:
721 722
                    kernel_args_type_list.append('const phi::Scalar&')
                    param = 'phi::Scalar(' + param + ')'
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
                else:
                    kernel_args_type_list.append(self.attrs['attr_info'][param][
                        0])
                kernel_args = kernel_args + param + ", "
            elif isinstance(param, bool):
                kernel_args = kernel_args + str(param).lower() + ", "
            else:
                kernel_args = kernel_args + str(param) + ", "

        for out_type in self.outputs['types']:
            kernel_args_type_list.append(out_trans_map[out_type])

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

        return input_tensor_code, kernel_args[:-2], kernel_signature

739 740
    # Override by child class
    def gene_return_code(self):
741
        return "return api_output;"
742

743
    # Override by child class
744 745 746 747 748
    def gene_output(self,
                    output_type_list,
                    set_out_func,
                    code_indent,
                    inplace_flag=False):
749 750
        return None, None, None

751
    def gen_dense_tensor_kernel_code(self, code_indent, inplace_flag=False):
752 753 754
        input_tensors, kernel_args, kernel_signature = self.get_kernel_args(
            code_indent)
        outputs_args, kernel_output_names, output_create = self.gene_output(
755
            self.outputs['types'], 'SetKernelOutput', code_indent, inplace_flag)
756
        api_func_name = self.get_api_func_name() + ('_' if inplace_flag else '')
Z
zyfncg 已提交
757
        cudnn_args = '' if self.kernel[
758
            'use_gpudnn'] == 'false' else ', ' + self.kernel['use_gpudnn']
759
        return f"""
F
From00 已提交
760
{code_indent}  VLOG(6) << "{self.api} API kernel key: [" << kernel_backend << ", " << kernel_layout << ", "<< kernel_data_type << "]";
761
{code_indent}  const auto& kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
Z
zyfncg 已提交
762
{code_indent}      "{self.kernel['func'][0]}", {{kernel_backend, kernel_layout, kernel_data_type}}{cudnn_args});
763 764 765 766 767 768 769 770 771
{code_indent}  VLOG(6) << "{self.api} API kernel: " << kernel;

{code_indent}  auto* dev_ctx = GetDeviceContextByBackend(kernel_backend);
{input_tensors}
{output_create}
{self.gene_infer_meta(kernel_output_names, code_indent)}

{code_indent}  using kernel_signature = {kernel_signature};
{code_indent}  auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
772
{code_indent}  {{
C
chenjian 已提交
773
{code_indent}    paddle::platform::RecordEvent kernel_record_event(\"{api_func_name} compute\", paddle::platform::TracerEventType::OperatorInner, 1);
774 775
{code_indent}    (*kernel_fn)({kernel_args}, {outputs_args});
{code_indent}  }}
776

777
{code_indent}  {self.gene_return_code()}"""
778

779
    def gen_selected_rows_kernel_code(self, code_indent, inplace_flag=False):
780 781 782
        input_tensors, kernel_args, kernel_signature = self.get_selected_rows_kernel_args(
            code_indent)
        outputs_args, kernel_output_names, output_create = self.gene_output(
783 784
            self.outputs['types'], 'SetSelectedRowsKernelOutput', code_indent,
            inplace_flag)
785
        api_func_name = self.get_api_func_name() + ('_' if inplace_flag else '')
786
        return f"""
787
{code_indent}  auto kernel = phi::KernelFactory::Instance().SelectKernelOrThrowError(
788 789 790 791 792 793 794 795 796 797 798
{code_indent}      "{self.kernel['func'][1]}", {{kernel_backend, kernel_layout, kernel_data_type}});
{code_indent}  VLOG(6) << "{self.api} API SelectedRows kernel key: [" << kernel_backend << ", " << kernel_layout << ", "<< kernel_data_type << "]";
{code_indent}  VLOG(6) << "{self.api} API SelectedRows kernel: " << kernel;

{code_indent}  auto* dev_ctx = GetDeviceContextByBackend(kernel_backend);
{input_tensors}
{output_create}
{self.gene_infer_meta(kernel_output_names, code_indent)}

{code_indent}  using kernel_signature = {kernel_signature};
{code_indent}  auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
799
{code_indent}  {{
C
chenjian 已提交
800
{code_indent}    paddle::platform::RecordEvent kernel_record_event(\"{api_func_name} compute\", paddle::platform::TracerEventType::OperatorInner, 1);
801 802
{code_indent}    (*kernel_fn)({kernel_args}, {outputs_args});
{code_indent}  }}
803

804
{code_indent}  {self.gene_return_code()}"""
805

806
    def gene_base_api_code(self, inplace_flag=False):
807 808 809
        api_func_name = self.get_api_func_name()
        if inplace_flag and api_func_name[-1] != '_':
            api_func_name += '_'
810
        api_code = f"""
811
PADDLE_API {self.get_return_type(inplace_flag)} {api_func_name}({self.get_define_args(inplace_flag)}) {{
812
{self.gene_kernel_select()}
813
"""
814

815 816 817
        if self.support_selected_rows_kernel:
            code_indent = '  '
            return api_code + f"""
818
  if(kernel_type == KernelType::DENSE_TENSOR_KENREL){{
819
{self.gen_dense_tensor_kernel_code(code_indent, inplace_flag)}
820
  }} else {{
821
{self.gen_selected_rows_kernel_code(code_indent, inplace_flag)}
822
  }}
823
}}
824 825
"""

826 827 828 829
        else:
            code_indent = ''
            return api_code + self.gen_dense_tensor_kernel_code(
                code_indent, inplace_flag) + """
830
}
831 832
"""

833 834
    def gene_invoke_code(self, invoke_code, params_code):
        return f"""
835
PADDLE_API {self.get_return_type()} {self.api}({params_code}) {{
836 837 838
  return {invoke_code};
}}"""

839 840 841
    def gene_api_code(self):
        if self.is_base_api:
            api_code = self.gene_base_api_code()
842
            if len(self.inplace_map) > 0:
843 844 845
                api_code = api_code + self.gene_base_api_code(inplace_flag=True)
            return api_code

846
        else:
847 848
            invoke_func_name = self.invoke.split('(')[0].strip()
            if invoke_func_name in self.attrs['names']:
849
                # Adjust the param whose name is same with api invoked.
850
                pattern = r'\W' + invoke_func_name + '[^A-Za-z0-9_(]'
851 852 853 854 855 856 857

                def adjust_name(matched):
                    matched_str = matched.group()
                    return matched_str[0:-1] + '_val' + matched_str[-1]

                invoke_code = re.sub(pattern, adjust_name, self.invoke)
                params_code = re.sub(pattern, adjust_name,
858
                                     self.get_define_args())
859 860
            else:
                invoke_code = self.invoke
861 862
                params_code = self.get_define_args()
            return self.gene_invoke_code(invoke_code, params_code)