api_gen.py 14.4 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# 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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15 16 17
# 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 os
import yaml
import argparse
18
import re
19

20
from api_base import BaseAPI, PREFIX_TENSOR_NAME
21

22 23 24 25 26
inplace_out_type_map = {
    "Tensor": "Tensor&",
    "std::vector<Tensor>": "std::vector<Tensor>&"
}

27 28 29 30 31
inplace_optional_out_type_map = {
    "Tensor": "paddle::optional<Tensor>&",
    "std::vector<Tensor>": "paddle::optional<std::vector<Tensor>>&"
}

32

33
class ForwardAPI(BaseAPI):
34

35
    def __init__(self, api_item_yaml):
36
        super(ForwardAPI, self).__init__(api_item_yaml)
37 38
        self.is_dygraph_api, self.intermediate_outs = self.parse_intermediate(
            api_item_yaml)
39 40
        self.inplace_map, self.view_map = self.parse_inplace_and_view(
            api_item_yaml)
41 42 43 44 45 46 47

    def get_api_func_name(self):
        if self.is_dygraph_api:
            return self.api + '_intermediate'
        else:
            return self.api

Y
YuanRisheng 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    def gene_input(self, kernel_tensor_type=None, code_indent=''):
        kernel_param = self.kernel['param']
        input_name_tensor_map, input_tensor_code = super().gene_input(
            kernel_tensor_type, code_indent)

        # generate the input that is in view list
        for i, input_name in enumerate(self.inputs['names']):
            if input_name in self.view_map.values(
            ) and input_name not in input_name_tensor_map.keys():
                if kernel_tensor_type is None or kernel_tensor_type[0][
                        kernel_param.index(input_name)] == 'dense':
                    trans_flag = self.gene_trans_flag(input_name)
                    input_tensor_code = input_tensor_code + f"""
{code_indent}  auto {PREFIX_TENSOR_NAME}{input_name} = PrepareData({input_name}, kernel.InputAt(0), {trans_flag});"""
                else:
                    # do nothing
                    pass

        return input_name_tensor_map, input_tensor_code

68 69
    def parse_intermediate(self, api_item_yaml):
        if 'intermediate' in api_item_yaml:
70 71 72 73 74
            intermediate_outs = [
                item.strip()
                for item in api_item_yaml['intermediate'].split(',')
            ]
            return True, intermediate_outs
75
        else:
76
            return False, []
77

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    def parse_inplace_and_view(self, api_item_yaml):
        inplace_map, view_map = {}, {}
        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

103 104 105 106 107
    def get_return_type_with_intermediate(self, inplace_flag=False):
        out_type_list = []
        for i, out_type in enumerate(self.outputs['types']):
            out_name = self.outputs['names'][i].split('@')[0]
            if inplace_flag and out_name in self.inplace_map:
108 109 110 111 112
                if self.inplace_map[out_name] in self.optional_vars:
                    out_type_list.append(
                        inplace_optional_out_type_map[out_type])
                else:
                    out_type_list.append(inplace_out_type_map[out_type])
113 114
            else:
                out_type_list.append(out_type)
115

116 117
        if len(out_type_list) == 1:
            return out_type_list[0]
118
        else:
119 120 121 122 123 124 125
            return "std::tuple<" + ", ".join(out_type_list) + ">"

    def get_return_type(self, inplace_flag=False):
        out_type_list = []
        for i, out_type in enumerate(self.outputs['types']):
            out_name = self.outputs['names'][i].split('@')[0]
            if inplace_flag and out_name in self.inplace_map:
126 127 128 129 130
                if self.inplace_map[out_name] in self.optional_vars:
                    out_type_list.append(
                        inplace_optional_out_type_map[out_type])
                else:
                    out_type_list.append(inplace_out_type_map[out_type])
131 132 133 134 135 136 137
            elif self.is_dygraph_api or out_name not in self.intermediate_outs:
                out_type_list.append(out_type)

        if len(out_type_list) == 1:
            return out_type_list[0]
        else:
            return "std::tuple<" + ", ".join(out_type_list) + ">"
138 139 140

    def gene_return_code(self):
        if self.is_dygraph_api or len(self.intermediate_outs) == 0:
141
            return "return api_output;"
142 143 144
        else:
            return_out_list = []
            for i, name in enumerate(self.outputs['names']):
145
                if name.split('@')[0] not in self.intermediate_outs:
146 147
                    return_out_list.append(i)
            if len(return_out_list) == 1:
148
                return f"return std::get<{return_out_list[0]}>(api_output);"
149 150 151 152
            else:
                selected_code = [
                    f"std::get<{i}>(api_output)" for i in return_out_list
                ]
153
            return 'return std::make_tuple(' + ", ".join(selected_code) + ');'
154

155
    def gene_output(self,
156 157 158
                    out_dtype_list,
                    out_tensor_type_list=None,
                    code_indent='',
159
                    inplace_flag=False):
160
        kernel_output = []
161
        output_names = []
Z
zyfncg 已提交
162
        output_create = ""
163
        return_type = self.get_return_type_with_intermediate(inplace_flag)
Z
zyfncg 已提交
164

165
        if len(out_dtype_list) == 1:
166
            kernel_output.append('kernel_out')
167
            output_names.append('kernel_out')
168 169 170
            inplace_assign = " = " + self.inplace_map[
                self.outputs['names'][0]] if inplace_flag and self.outputs[
                    'names'][0] in self.inplace_map else ""
Z
zyfncg 已提交
171
            output_create = f"""
172
{code_indent}  {return_type} api_output{inplace_assign};"""
173 174
            set_out_func = 'SetKernelOutput' if out_tensor_type_list is None or out_tensor_type_list[
                0] == 'dense' else 'SetSelectedRowsKernelOutput'
175
            if return_type == 'std::vector<Tensor>':
176
                assert self.outputs['out_size_expr'][0] is not None, \
177
                     f"{self.api}: The out size expr : '{{expr}}' should be set when output has Tensor[]. You can refer 'split' api."
178
                output_create = output_create + f"""
Z
zyfncg 已提交
179
{code_indent}  auto kernel_out = {set_out_func}({self.outputs['out_size_expr'][0]}, &api_output);"""
180 181 182

            else:
                output_create = output_create + f"""
Z
zyfncg 已提交
183
{code_indent}  auto kernel_out = {set_out_func}(&api_output);"""
Z
zyfncg 已提交
184

185 186 187 188 189 190 191
            if not inplace_flag and self.view_map is not None and self.outputs[
                    'names'][0] in self.view_map:
                output_create = output_create + f"""
{code_indent}  kernel_out->ShareBufferWith(*{PREFIX_TENSOR_NAME}{self.view_map[self.outputs['names'][0]]});
{code_indent}  kernel_out->ShareInplaceVersionCounterWith(*{PREFIX_TENSOR_NAME}{self.view_map[self.outputs['names'][0]]});
{code_indent}  VLOG(3) << "Perform View between Output and Input Tensor, share allocation and inplace version.";"""

192
        elif len(out_dtype_list) > 1:
Z
zyfncg 已提交
193
            output_create = f"""
194 195 196 197 198 199 200 201
{code_indent}  {return_type} api_output;"""

            if inplace_flag:
                output_create = f"""
{code_indent}  {return_type} api_output{{"""

                for out_name in self.outputs['names']:
                    if out_name in self.inplace_map:
202
                        output_create += self.inplace_map[out_name] + ', '
203 204 205
                    else:
                        output_create += 'Tensor(), '
                output_create = output_create[:-2] + '};'
Z
zyfncg 已提交
206

207
            for i in range(len(out_dtype_list)):
208
                kernel_output.append(f'kernel_out_{i}')
209
                output_names.append(f'kernel_out_{i}')
210 211 212 213 214 215 216 217
                set_out_func = 'SetKernelOutput' if out_tensor_type_list is None or out_tensor_type_list[
                    i] == 'dense' else 'SetSelectedRowsKernelOutput'

                get_out_code = f"&std::get<{i}>(api_output)"
                if self.outputs['names'][
                        i] in self.inplace_map and self.inplace_map[
                            self.outputs['names'][i]] in self.optional_vars:
                    get_out_code = f"std::get<{i}>(api_output).get_ptr()"
218

219
                if out_dtype_list[i] == 'std::vector<Tensor>':
220
                    assert self.outputs['out_size_expr'][i] is not None, \
221
                        f"{self.api}: The out size expr : '{{expr}}' should be set when output has Tensor[]. You can refer 'split' api."
222 223 224 225 226 227 228
                    # Special case for inplace vector and inplace optional<vector>
                    if self.outputs['names'][i] in self.inplace_map:
                        set_out_func = "SetInplaceVectorKernelOutput"
                        if self.inplace_map[self.outputs['names']
                                            [i]] in self.optional_vars:
                            set_out_func = "SetInplaceOptionalVectorKernelOutput"
                            get_out_code = f"std::get<{i}>(api_output)"
229
                    output_create = output_create + f"""
Z
zyfncg 已提交
230
{code_indent}  auto kernel_out_{i} = {set_out_func}({self.outputs['out_size_expr'][i]}, {get_out_code});"""
231 232 233

                else:
                    output_create = output_create + f"""
Z
zyfncg 已提交
234
{code_indent}  auto kernel_out_{i} = {set_out_func}({get_out_code});"""
Z
zyfncg 已提交
235

236 237
                if not inplace_flag and self.view_map is not None and self.outputs[
                        'names'][i] in self.view_map:
Y
YuanRisheng 已提交
238 239 240 241 242 243 244 245 246
                    if out_dtype_list[i] == 'Tensor':
                        output_create = output_create + f"""
    {code_indent}  kernel_out_{i}->ShareBufferWith(*{PREFIX_TENSOR_NAME}{self.view_map[self.outputs['names'][i]]});
    {code_indent}  kernel_out_{i}->ShareInplaceVersionCounterWith(*{PREFIX_TENSOR_NAME}{self.view_map[self.outputs['names'][i]]});
    {code_indent}  VLOG(3) << "Perform View between Output and Input Tensor, share allocation and inplace version.";"""
                    else:
                        raise ValueError(
                            "{} : Output error: only support Tensor type when use view in yaml. But get {}"
                            .format(self.api, out_dtype_list[i]))
Z
zyfncg 已提交
247 248 249 250 251
        else:
            raise ValueError(
                "{} : Output error: the output should not be empty.".format(
                    self.api))

252
        return kernel_output, output_names, output_create
Z
zyfncg 已提交
253

254 255 256

def header_include():
    return """
257 258
#include <tuple>

259 260
#include "paddle/phi/api/include/tensor.h"
#include "paddle/phi/common/scalar.h"
261
#include "paddle/phi/common/int_array.h"
262
#include "paddle/utils/optional.h"
263 264 265 266 267 268 269 270 271 272
"""


def source_include(header_file_path):
    return f"""
#include "{header_file_path}"
#include <memory>

#include "glog/logging.h"

273
#include "paddle/phi/api/lib/api_custom_impl.h"
274
#include "paddle/phi/api/lib/api_gen_utils.h"
275 276 277 278 279 280 281
#include "paddle/phi/api/lib/data_transform.h"
#include "paddle/phi/api/lib/kernel_dispatch.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/infermeta/binary.h"
#include "paddle/phi/infermeta/multiary.h"
#include "paddle/phi/infermeta/nullary.h"
#include "paddle/phi/infermeta/unary.h"
H
hong 已提交
282
#include "paddle/phi/infermeta/ternary.h"
283 284

#include "paddle/fluid/platform/profiler/event_tracing.h"
285
#include "paddle/fluid/platform/profiler/supplement_tracing.h"
Z
zyfncg 已提交
286 287

DECLARE_bool(conv2d_disable_cudnn);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
"""


def api_namespace():
    return ("""
namespace paddle {
namespace experimental {

""", """

}  // namespace experimental
}  // namespace paddle
""")


303
def generate_api(api_yaml_path, header_file_path, source_file_path):
304 305 306 307 308 309 310
    apis = []

    for each_api_yaml in api_yaml_path:
        with open(each_api_yaml, 'r') as f:
            api_list = yaml.load(f, Loader=yaml.FullLoader)
            if api_list:
                apis.extend(api_list)
311 312 313 314 315 316 317 318 319 320

    header_file = open(header_file_path, 'w')
    source_file = open(source_file_path, 'w')

    namespace = api_namespace()

    header_file.write("#pragma once\n")
    header_file.write(header_include())
    header_file.write(namespace[0])

321
    include_header_file = "paddle/phi/api/include/api.h"
322 323 324 325
    source_file.write(source_include(include_header_file))
    source_file.write(namespace[0])

    for api in apis:
326 327
        foward_api = ForwardAPI(api)
        if foward_api.is_dygraph_api:
328
            foward_api.is_dygraph_api = False
329 330 331

        header_file.write(foward_api.gene_api_declaration())
        source_file.write(foward_api.gene_api_code())
332 333 334

    header_file.write(namespace[1])
    source_file.write(namespace[1])
335

336 337 338 339 340 341 342
    header_file.close()
    source_file.close()


def main():
    parser = argparse.ArgumentParser(
        description='Generate PaddlePaddle C++ API files')
343 344 345
    parser.add_argument('--api_yaml_path',
                        help='path to api yaml file',
                        nargs='+',
C
Chen Weihang 已提交
346
                        default='paddle/phi/api/yaml/ops.yaml')
347 348 349 350 351 352 353 354

    parser.add_argument('--api_header_path',
                        help='output of generated api header code file',
                        default='paddle/phi/api/include/api.h')

    parser.add_argument('--api_source_path',
                        help='output of generated api source code file',
                        default='paddle/phi/api/lib/api.cc')
355 356 357 358 359 360 361

    options = parser.parse_args()

    api_yaml_path = options.api_yaml_path
    header_file_path = options.api_header_path
    source_file_path = options.api_source_path

362
    generate_api(api_yaml_path, header_file_path, source_file_path)
363 364 365 366


if __name__ == '__main__':
    main()