gen_utils.py 14.2 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 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
# 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

PREFIX_TENSOR_NAME = 'dense_'


def parse_args(api_name, args_str):
    """
    Returns:
       { inputs : {
             names : [] // list of input names
             input_info : { input_name : type }
         }
         attrs: {
             names : [] // list of attribute names
             attr_info : { attr_name : (type, default_value)}
         }
         args_declare : "str" // str of funtion params with default value. Example: (..., bool flag=false)
         args_define : "str" // str of funtion params without default value. Example: (..., bool flag)
       }
    """
    inputs = {'names': [], 'input_info': {}}
    attrs = {'names': [], 'attr_info': {}}
    args_str = args_str.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(',')
    input_types = [
        'const Tensor&', 'const Tensor &', 'const std::vector<Tensor>&',
        'const std::vector<Tensor> &'
    ]
    attr_types = ['const Scalar&', 'const Scalar &', 'const ScalarArray&', 'const ScalarArray &', \
                  'int', 'int32_t', 'int64_t', 'size_t', 'float', 'double', 'bool', \
                  'const std::vector<int64_t>&', 'Backend', 'DataLayout', 'DataType']
    args_declare_str = ""
    args_define_str = ""

    for item in args_list:
        item = item.strip()
        # match the input tensor
        has_input = False
        for in_type in input_types:
            if item.startswith(in_type):
                input_name = item[len(in_type):].strip()
                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"

                inputs['names'].append(input_name)
                inputs['input_info'][input_name] = in_type
                args_declare_str = args_declare_str + in_type + ' ' + input_name + ', '
                args_define_str = args_define_str + in_type + ' ' + input_name + ', '
                has_input = True
                break
        if has_input:
            continue

        # match the attribute
        for attr_type in attr_types:
            if item.startswith(attr_type):
                attr_name = item[len(attr_type):].strip()
                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()

                default_value_str = "" if default_value is None else '=' + default_value
                args_declare_str = args_declare_str + attr_type + ' ' + attr_name + default_value_str + ', '
                args_define_str = args_define_str + attr_type + ' ' + attr_name + ', '
                attrs['names'].append(attr_name)
                attrs['attr_info'][attr_name] = (attr_type, default_value)
                break

    args = {
        'inputs': inputs,
        'attrs': attrs,
        'args_declare': args_declare_str[:-2],
        'args_define': args_define_str[:-2]
    }
    return args


def parse_output(api_name, output_config):
    def parse_output_item(output_item):
        alllowd_output_types = ['Tensor', 'std::vector<Tensor>']
        if re.search(r'\(\w*\)', output_item):
            result = re.search(
                r"(?P<out_type>[a-zA-Z0-9_<>]+)\s*\((?P<name>\w+)\)",
                output_item)
            out_type = result.group('out_type')
            assert out_type in alllowd_output_types, \
                f"{api_name} : Output type error: the output type only support Tensor and std::vector<Tensor>, \
                  but now is {out_type}."

            return out_type, result.group('name')

        else:
            if output_item.strip() in alllowd_output_types:
                return output_item.strip(), 'out'
            else:
                raise ValueError(
                    "{} : Output type error: the output type only support Tensor and std::vector<Tensor>, \
                  but now is {}.".format(api_name, out_type))

    temp_list = output_config.split(',')

    if len(temp_list) == 1:
        out_type, out_name = parse_output_item(temp_list[0])
        return out_type, out_name
    else:
        out_type_list = []
        out_name_list = []
        for output_item in temp_list:
            out_type, out_name = parse_output_item(output_item)
            out_type_list.append(out_type)
            out_name_list.append(out_name)

        return "std::tuple<" + ",".join(out_type_list) + ">", ", ".join(
            out_name_list)


def gene_kernel_select(api, input_names, attrs, kernel) -> str:

    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']:
        if attrs['attr_info'][attr_name][0] == 'Backend':
            assert kernel['backend'] is not None, \
                f"{api} api: When there is a parameter with 'Backend' type in attributes, you must set backend of kernel manually."
            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
    kernel_select_code = ""
    if kernel['backend'] is not None:
        if '>' in kernel['backend']:
            vars_list = kernel['backend'].split('>')
            assert len(
                vars_list
            ) == 2, f"{api} api: The number of params to set backend 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] == 'Backend'), \
                f"{api} api: When use '>' to set kernel backend, the first param should be a attribute with Backend type."
            kernel_select_code = kernel_select_code + f"""
  kernel_backend = ParseBackendWithInputOrder({vars_list[0].strip()}, {vars_list[1].strip()});
"""

        else:
            args_str = ""
            for ele in kernel['backend'].split(','):
                args_str = args_str + ele.strip() + ', '
            kernel_select_code = kernel_select_code + f"""
  kernel_backend = ParseBackend({args_str[:-2]});
"""

    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
            ) == 1, f"{api} api: The number of params to set data_type only allows 2, but received {len(vars_list)}."
            kernel_select_code = kernel_select_code + f"""
  kernel_data_type = ParseDataType({vars_list[0].strip()});
"""

    if len(input_names) == 0:
        assert attr_backend_count > 0 and attr_layout_count > 0 and attr_data_type_count > 0, \
            f"{api} api: When there is no input tensor, the args must have 'Backend', 'DataLayout' and 'DataType'."

    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:
        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});
    auto kernel_key = kernel_key_set.GetHigestPriorityKernelKey();
    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();
    }}
  }}"""

    kernel_select_code = kernel_select_code + f"""
  auto kernel = pten::KernelFactory::Instance().SelectKernelOrThrowError(
      "{kernel['func']}", {{kernel_backend, kernel_layout, kernel_data_type}});
  VLOG(6) << "{api} API kernel key: [" << kernel_backend << ", " << kernel_layout << ", "<< kernel_data_type << "]";
  VLOG(6) << "{api} API kernel: " << kernel;"""

    return kernel_select_code


def gene_infer_meta(input_names, attr_names, infer_meta) -> str:
    infer_meta_params = infer_meta['param'] if infer_meta[
        'param'] is not None else input_names + attr_names
    param_code = ""
    for param in infer_meta_params:
        if param in input_names:
            param_code = param_code + "GetDenseTensorMeta(*" + PREFIX_TENSOR_NAME + param + "), "
        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) + ", "

    param_code = param_code[:-2]
    return f"""
  auto out_meta = pten::{infer_meta['func']}({param_code});
"""


def get_kernel_args(input_names, attrs, kernel_param):
    input_tensor_code = ""
    for input_name in input_names:
        # set input code
        input_tensor_code = input_tensor_code + f"""
  auto {PREFIX_TENSOR_NAME}{input_name} = TensorToDenseTensor({input_name});"""

    attr_names = attrs['names']
    if kernel_param is None:
        kernel_param = input_names + attr_names

    kernel_args = "*dev_ctx, "
    for param in kernel_param:
        if param in input_names:
            kernel_args = kernel_args + "*" + PREFIX_TENSOR_NAME + param + ", "
        elif param in attr_names:
            # set attr for kernel_context
            if 'ScalarArray' in attrs['attr_info'][param][0]:
                param = 'pten::ScalarArray(' + param + ')'
            elif 'Scalar' in attrs['attr_info'][param][0]:
                param = 'pten::Scalar(' + param + ')'
            kernel_args = kernel_args + param + ", "
        elif isinstance(param, bool):
            kernel_args = kernel_args + str(param).lower() + ", "
        else:
            kernel_args = kernel_args + str(param) + ", "
    return input_tensor_code, kernel_args[:-2]


def gene_output(output_type):
    kernel_output = ""
    output_create = f"""
  {output_type} out;"""

    if output_type == 'Tensor' or output_type == 'std::vector<Tensor>':
        kernel_output = 'dense_out'
        output_create = output_create + """
  auto dense_out = SetKernelOutput(out_meta, kernel_backend, &out);"""
    elif re.match(r'std::tuple<.*>$', output_type):
        out_num = output_type.count('Tensor')
        for i in range(out_num):
            kernel_output = kernel_output + f'dense_out_{i}, '
            output_create = output_create + f"""
  auto dense_out_{i} = SetKernelOutput(std::get<{i}>(out_meta), kernel_backend, &std::get<{i}>(out));"""

        kernel_output = kernel_output[:-2]

    return kernel_output, output_create