sparse_bw_api_gen.py 6.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Copyright (c) 2022 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 yaml
import argparse

from sparse_api_gen import SparseAPI
from backward_api_gen import BackwardAPI


class SparseBackwardAPI(SparseAPI, BackwardAPI):
23

24 25 26 27 28 29
    def __init__(self, bw_api_item_yaml):
        BackwardAPI.__init__(self, bw_api_item_yaml)

    def get_api_func_name(self):
        return self.api

30 31 32
    def gene_kernel_backend_select(self):
        return BackwardAPI.gene_kernel_backend_select(self)

33 34
    def get_return_type(self, inplace_flag=False):
        return BackwardAPI.get_return_type(self)
35 36

    def gene_return_code(self):
37
        return "return;"
38

39 40 41
    def gene_api_declaration(self):
        return SparseAPI.gene_api_declaration(self)

42
    def get_declare_args(self, inplace_flag=False):
43 44
        return BackwardAPI.get_declare_args(self)

45
    def get_define_args(self, inplace_flag=False):
46 47
        return BackwardAPI.get_define_args(self)

48
    def gene_output(self,
49 50 51
                    out_dtype_list,
                    out_tensor_type_list=None,
                    code_indent='',
52
                    inplace_flag=False):
53
        kernel_output = []
54 55
        output_names = []
        output_create = ""
56 57 58 59 60
        output_type_map = {
            'dense': 'TensorType::DENSE_TENSOR',
            'sparse_coo': 'TensorType::SPARSE_COO',
            'sparse_csr': 'TensorType::SPARSE_CSR'
        }
61

62
        if len(out_dtype_list) == 1:
63
            kernel_output.append('kernel_out')
64 65 66 67 68
            output_names.append('kernel_out')
            inplace_assign = " = " + self.inplace_map[self.outputs['names'][
                0]] if inplace_flag and self.inplace_map is not None and self.outputs[
                    'names'][0] in self.inplace_map else ""
            output_create = f"""
69
    auto kernel_out = SetSparseKernelOutput({self.outputs['names'][0]}, {output_type_map[out_dtype_list[0]]});"""
70

71
        elif len(out_dtype_list) > 1:
72
            output_create = ""
73

74
            for i, out_type_item in enumerate(out_dtype_list):
75
                kernel_output.append(f'kernel_out_{i}')
76
                output_names.append(f'kernel_out_{i}')
77 78 79
                if inplace_flag and self.inplace_map is not None and self.outputs[
                        'names'][i] in self.inplace_map:
                    output_create = output_create + f"""
80
    *{self.outputs['names'][i]} = {self.inplace_map[self.outputs['names'][i]]};"""
81 82

                output_create = output_create + f"""
83
    auto kernel_out_{i} = SetSparseKernelOutput({self.outputs['names'][i]}, {output_type_map[out_dtype_list[i]]});"""
84 85 86 87 88 89 90 91 92 93 94 95 96

        else:
            raise ValueError(
                "{} : Output error: the output should not be empty.".format(
                    self.api))

        return kernel_output, output_names, output_create


def header_include():
    return """
#include "paddle/phi/api/include/tensor.h"
#include "paddle/phi/common/scalar.h"
97
#include "paddle/phi/common/int_array.h"
98 99 100 101 102 103 104 105 106 107 108
#include "paddle/utils/optional.h"
"""


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

#include "glog/logging.h"

109
#include "paddle/phi/api/include/sparse_api.h"
110 111 112
#include "paddle/phi/api/lib/api_gen_utils.h"
#include "paddle/phi/api/lib/kernel_dispatch.h"
#include "paddle/phi/core/kernel_registry.h"
Z
zhangkaihuo 已提交
113 114 115 116 117 118 119 120

#include "paddle/phi/infermeta/unary.h"
#include "paddle/phi/infermeta/binary.h"
#include "paddle/phi/infermeta/backward.h"

#include "paddle/phi/infermeta/sparse/unary.h"
#include "paddle/phi/infermeta/sparse/binary.h"
#include "paddle/phi/infermeta/sparse/backward.h"
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
"""


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

""", """

}  // namespace sparse
}  // 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/phi/api/backward/sparse_bw_api.h"
    source_file.write(source_include(include_header_file))
    source_file.write(namespace[0])

    for api in apis:
        sparse_bw_api = SparseBackwardAPI(api)
        header_file.write(sparse_bw_api.gene_api_declaration())
        source_file.write(sparse_bw_api.gene_api_code())

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

    header_file.close()
    source_file.close()


def main():
    parser = argparse.ArgumentParser(
        description='Generate PaddlePaddle C++ Sparse API files')
170 171
    parser.add_argument('--api_yaml_path',
                        help='path to sparse api yaml file',
C
Chen Weihang 已提交
172
                        default='paddle/phi/api/yaml/sparse_backward.yaml')
173

174 175 176
    parser.add_argument('--api_header_path',
                        help='output of generated api header code file',
                        default='paddle/phi/api/backward/sparse_bw_api.h')
177

178 179 180
    parser.add_argument('--api_source_path',
                        help='output of generated api source code file',
                        default='paddle/phi/api/lib/sparse_bw_api.cc')
181 182 183 184 185 186 187 188 189 190 191 192

    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()