api_gen.py 7.9 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 18
# 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

19 20
import gen_utils

21 22 23 24 25 26 27

class API:
    prefix_tensor_name = 'dense_'

    def __init__(self, api_item_yaml):
        self.api = api_item_yaml['api']
        # args:
28
        #   inputs:
29
        #     names : [], list of input names
30
        #     input_info : {input_name : type}
31 32
        #   attrs:
        #     names : [], list of attribute names
33 34
        #     attr_info : { attr_name : (type, default_values)}
        self.args = gen_utils.parse_args(self.api, api_item_yaml['args'])
Z
zyfncg 已提交
35 36 37 38 39 40
        self.out_type_list, _ = gen_utils.parse_output(self.api,
                                                       api_item_yaml['output'])
        self.return_type = self.out_type_list[0] if len(
            self.out_type_list) == 1 else "std::tuple<" + ",".join(
                self.out_type_list) + ">"

41 42 43 44 45 46 47 48 49 50 51 52 53
        self.is_base_api = True
        if 'invoke' in api_item_yaml:
            self.is_base_api = False
            self.invoke = api_item_yaml['invoke']
        else:
            self.kernel = api_item_yaml['kernel']
            if 'backend' not in self.kernel or len(self.kernel['backend']) == 0:
                self.kernel['backend'] = None
            if 'layout' not in self.kernel or len(self.kernel['layout']) == 0:
                self.kernel['layout'] = None
            if 'data_type' not in self.kernel or len(self.kernel[
                    'data_type']) == 0:
                self.kernel['data_type'] = None
54
            if 'param' not in self.kernel:
55 56 57
                self.kernel['param'] = None

            self.infer_meta = api_item_yaml['infer_meta']
58
            if 'param' not in self.infer_meta:
59 60
                self.infer_meta['param'] = None

61 62 63 64 65 66 67 68 69 70 71 72
            self.data_transform = {
                'skip_transform': [],
                'support_trans_dtype': []
            }
            if 'data_transform' in api_item_yaml:
                if 'skip_transform' in api_item_yaml['data_transform']:
                    self.data_transform['skip_transform'] = api_item_yaml[
                        'data_transform']['skip_transform']
                if 'support_trans_dtype' in api_item_yaml['data_transform']:
                    self.data_transform['support_trans_dtype'] = api_item_yaml[
                        'data_transform']['support_trans_dtype']

73 74
    def gene_api_declaration(self):
        return f"""
Z
zyfncg 已提交
75
PADDLE_API {self.return_type} {self.api}({self.args['args_declare']});
76 77
"""

Z
zyfncg 已提交
78 79
    def gene_output(self, output_type_list):
        kernel_output = ""
80
        output_names = []
Z
zyfncg 已提交
81 82 83 84
        output_create = ""

        if len(output_type_list) == 1:
            kernel_output = 'dense_out'
85
            output_names.append('dense_out')
Z
zyfncg 已提交
86 87
            output_create = f"""
  {self.return_type} out;
88
  auto dense_out = SetKernelOutput(kernel_backend, &out);"""
Z
zyfncg 已提交
89 90 91 92 93 94 95

        elif len(output_type_list) > 1:
            output_create = f"""
  {self.return_type} out;"""

            for i in range(len(output_type_list)):
                kernel_output = kernel_output + f'dense_out_{i}, '
96
                output_names.append(f'dense_out_{i}')
Z
zyfncg 已提交
97
                output_create = output_create + f"""
98
  auto dense_out_{i} = SetKernelOutput(kernel_backend, &std::get<{i}>(out));"""
Z
zyfncg 已提交
99 100 101 102 103 104 105

            kernel_output = kernel_output[:-2]
        else:
            raise ValueError(
                "{} : Output error: the output should not be empty.".format(
                    self.api))

106
        return kernel_output, output_names, output_create
Z
zyfncg 已提交
107

108 109
    def gene_api_code(self):
        if self.is_base_api:
110 111
            input_tensors, kernel_args, kernel_signature = gen_utils.get_kernel_args(
                self.args['inputs'], self.args['attrs'], self.out_type_list,
112
                self.kernel['param'], self.data_transform)
113 114
            outputs_args, output_names, output_create = self.gene_output(
                self.out_type_list)
115
            return f"""
Z
zyfncg 已提交
116
PADDLE_API {self.return_type} {self.api}({self.args["args_define"]}) {{
117
{gen_utils.gene_kernel_select(self.api, self.args['inputs']['names'], self.args['attrs'], self.kernel)}
118 119

  auto* dev_ctx = GetDeviceContextByBackend(kernel_backend);
120
{input_tensors}
121
{output_create}
122
{gen_utils.gene_infer_meta(self.args['inputs']['names'], self.args['attrs']['names'], output_names, self.infer_meta)}
123 124
  using kernel_signature = {kernel_signature};
  auto* kernel_fn = kernel.GetVariadicKernelFn<kernel_signature>();
125
  (*kernel_fn)({kernel_args}, {outputs_args});
126 127 128 129 130 131 132

  return out;
}}
"""

        else:
            return f"""
Z
zyfncg 已提交
133
PADDLE_API {self.return_type} {self.api}({self.args["args_define"]}) {{
134 135 136 137 138 139 140
  return {self.invoke};
}}
"""


def header_include():
    return """
141 142
#include <tuple>

143 144 145 146 147 148 149 150 151 152 153 154 155 156
#include "paddle/pten/api/include/tensor.h"
#include "paddle/pten/common/scalar.h"
#include "paddle/pten/common/scalar_array.h"
"""


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

#include "glog/logging.h"

#include "paddle/pten/api/lib/api_registry.h"
157
#include "paddle/pten/api/lib/api_utils.h"
158
#include "paddle/pten/api/lib/data_transform.h"
159
#include "paddle/pten/api/lib/kernel_dispatch.h"
160
#include "paddle/pten/api/lib/utils/storage.h"
161
#include "paddle/pten/core/kernel_registry.h"
162 163 164 165
#include "paddle/pten/infermeta/binary.h"
#include "paddle/pten/infermeta/multiary.h"
#include "paddle/pten/infermeta/nullary.h"
#include "paddle/pten/infermeta/unary.h"
166
#include "paddle/pten/kernels/declarations.h"
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
"""


def api_register():
    return """
PT_REGISTER_API(Math);
"""


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

""", """

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


def generate_api(api_yaml_path, header_file_path, source_file_path):

    with open(api_yaml_path, 'r') as f:
        apis = yaml.load(f, Loader=yaml.FullLoader)
    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])

    include_header_file = "paddle/pten/api/include/api.h"
    source_file.write(source_include(include_header_file))
    source_file.write(namespace[0])

    for api in apis:
        api_code = API(api)
        print(api_code.gene_api_declaration())
        header_file.write(api_code.gene_api_declaration())
        source_file.write(api_code.gene_api_code())

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

    header_file.close()
    source_file.close()


def main():
    parser = argparse.ArgumentParser(
        description='Generate PaddlePaddle C++ API files')
    parser.add_argument(
        '--api_yaml_path',
224
        help='path to api yaml file',
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        default='python/paddle/utils/code_gen/api.yaml')
    parser.add_argument(
        '--api_header_path',
        help='output of generated api header code file',
        default='paddle/pten/api/include/api.h')

    parser.add_argument(
        '--api_source_path',
        help='output of generated api source code file',
        default='paddle/pten/api/lib/api.cc')

    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

    generate_api(api_yaml_path, header_file_path, source_file_path)


if __name__ == '__main__':
    main()