backward_api_gen.py 8.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 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 os
import yaml
import argparse
import re

20
from api_base import BaseAPI
21 22


23
class BackwardAPI(BaseAPI):
24
    def __init__(self, backward_item_yaml):
25 26 27 28 29
        super(BackwardAPI, self).__init__(backward_item_yaml)
        self.check_args(backward_item_yaml['forward'])

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

31 32 33 34 35 36 37
    def parse_forward_config(self, forward_config):
        # api_name (const Tensor& input, ... , int attr, ...) -> Tensor(out)
        result = re.search(
            r"(?P<api>[a-z][a-z0-9_]+)\s*(?P<args>\([^\)]+\))\s*->[^\(]*\((?P<outputs>[^\)]+)\)",
            forward_config)
        api = result.group('api')
        outputs = [item.strip() for item in result.group('outputs').split(',')]
38 39
        fw_inputs, fw_attrs, _, = self.parse_input_and_attr(
            api, result.group('args'))
40

41
        return api, fw_inputs, fw_attrs, outputs
42

43
    def check_args(self, forward_config):
44 45 46 47 48
        # parse the forward and backward config
        _, fw_inputs, fw_attrs, fw_outputs = self.parse_forward_config(
            forward_config)

        # check the inputs of backward
49
        for input in self.inputs['names']:
50 51 52 53
            if input not in fw_inputs and input not in fw_outputs:
                if input.endswith('_grad'):
                    original_name = input[:-5]
                    assert original_name in fw_outputs, \
54 55
                        f"{self.api} : Input Tensor error: the input tensor({input}) of backward should be an input or output or grad of output in forward api. \
                         Please check the forward of {self.api} in yaml."
56 57

        # check the attributes of backward
58 59 60 61
        for attr in self.attrs['names']:
            assert attr in fw_attrs['names'] and self.attrs['attr_info'][attr][0] == fw_attrs['attr_info'][attr][0], \
                f"{self.api} : Attribute error: The attribute({attr}) of backward isn't consistent with forward api. \
                 Please check the args of {self.api} in yaml."
62 63

        # check the output of backward
64
        assert len(self.outputs['types']) <= len(fw_inputs['names']), \
65
            f"{self.api} : Output error: The number of outputs should be less then the number of inputs of forward api. \
66
             Please check the output of {self.api} in yaml."
67

68 69 70
    def get_return_type(self, out_type_list):
        return out_type_list[0] if len(
            out_type_list) == 1 else "std::vector<std::vector<Tensor>>"
71

72 73 74 75 76
    def gene_output(self,
                    output_type_list,
                    set_out_func,
                    code_indent,
                    inplace_flag=False):
Z
zyfncg 已提交
77
        kernel_output = ""
78
        output_names = []
Z
zyfncg 已提交
79 80 81
        output_create = ""

        if len(output_type_list) == 1:
82 83
            kernel_output = 'kernel_out'
            output_names.append('kernel_out')
84 85 86
            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 ""
Z
zyfncg 已提交
87
            output_create = f"""
88
{code_indent}  {self.outputs['return_type']} out{inplace_assign};
89
{code_indent}  auto kernel_out = {set_out_func}(kernel_backend, &out);"""
Z
zyfncg 已提交
90 91 92

        elif len(output_type_list) > 1:
            output_create = f"""
93
{code_indent}  {self.outputs['return_type']} out({len(output_type_list)});"""
Z
zyfncg 已提交
94 95

            for i, out_type_item in enumerate(output_type_list):
96 97
                kernel_output = kernel_output + f'kernel_out_{i}, '
                output_names.append(f'kernel_out_{i}')
98 99
                if out_type_item == 'Tensor':
                    get_out_code = f'&out[{i}][0]'
100 101 102 103 104 105 106
                    if inplace_flag and self.inplace_map is not None and self.outputs[
                            'names'][i] in self.inplace_map:
                        output_create = output_create + f"""
{code_indent}  out[{i}].emplace_back({self.inplace_map[self.outputs['names'][i]]});"""

                    else:
                        output_create = output_create + f"""
107
{code_indent}  out[{i}].emplace_back();"""
108 109 110

                else:
                    get_out_code = f'&out[{i}]'
111 112 113 114 115
                    if inplace_flag and self.inplace_map is not None and self.outputs[
                            'names'][i] in self.inplace_map:
                        output_create = output_create + f"""
{code_indent}  out[{i}] = {self.inplace_map[self.outputs['names'][i]]};"""

Z
zyfncg 已提交
116
                output_create = output_create + f"""
117
{code_indent}  auto kernel_out_{i} = {set_out_func}(kernel_backend, {get_out_code});"""
Z
zyfncg 已提交
118 119 120 121 122

            kernel_output = kernel_output[:-2]
        else:
            raise ValueError(
                "{} : Output error: the output should not be empty.".format(
123
                    self.api))
Z
zyfncg 已提交
124

125
        return kernel_output, output_names, output_create
Z
zyfncg 已提交
126

127 128 129 130 131

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

132 133 134
#include "paddle/phi/api/include/tensor.h"
#include "paddle/phi/common/scalar.h"
#include "paddle/phi/common/scalar_array.h"
135 136 137 138 139 140 141 142 143 144
"""


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

#include "glog/logging.h"

145
#include "paddle/phi/api/lib/api_custom_impl.h"
146 147 148 149 150 151 152 153
#include "paddle/phi/api/lib/api_registry.h"
#include "paddle/phi/api/lib/api_utils.h"
#include "paddle/phi/api/lib/data_transform.h"
#include "paddle/phi/api/lib/kernel_dispatch.h"
#include "paddle/phi/api/lib/utils/storage.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/api/include/api.h"
#include "paddle/phi/infermeta/backward.h"
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
"""


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

""", """

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


def generate_backward_api(backward_yaml_path, header_file_path,
                          source_file_path):

    with open(backward_yaml_path, 'r') as f:
        bw_apis = yaml.load(f, Loader=yaml.FullLoader)
    header_file = open(header_file_path, 'w')
    source_file = open(source_file_path, 'w')

    namespace = backward_api_namespace()

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

183
    include_header_file = "paddle/phi/api/backward/backward_api.h"
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
    source_file.write(source_include(include_header_file))
    source_file.write(namespace[0])

    for bw_api in bw_apis:
        bw_api = BackwardAPI(bw_api)
        header_file.write(bw_api.gene_api_declaration())
        source_file.write(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++ backward API files')
    parser.add_argument(
        '--backward_yaml_path',
        help='path to backward yaml file',
        default='python/paddle/utils/code_gen/backward.yaml')
    parser.add_argument(
        '--backward_header_path',
        help='output of generated backward header code file',
209
        default='paddle/phi/api/backward/backward_api.h')
210 211 212 213

    parser.add_argument(
        '--backward_source_path',
        help='output of generated backward source code file',
214
        default='paddle/phi/api/lib/backward_api.cc')
215 216 217 218 219 220 221 222 223 224 225 226 227

    options = parser.parse_args()

    backward_yaml_path = options.backward_yaml_path
    header_file_path = options.backward_header_path
    source_file_path = options.backward_source_path

    generate_backward_api(backward_yaml_path, header_file_path,
                          source_file_path)


if __name__ == '__main__':
    main()