generate_op.py 20.0 KB
Newer Older
1
# Copyright (c) 2022 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 19
# 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 argparse
import os
from pathlib import Path

import yaml
20
from filters import (
21 22
    cartesian_prod_mapping,
    to_input_name,
23 24
    to_int_array_tensor_name,
    to_int_array_tensors_name,
25 26 27 28
    to_op_attr_type,
    to_opmaker_name,
    to_opmaker_name_cstr,
    to_pascal_case,
29
    to_scalar_tensor_name,
30
)
31 32
from jinja2 import Environment, FileSystemLoader, StrictUndefined
from parse_utils import to_named_dict
33
from tests import (
34
    is_base_op,
35
    is_initializer_list,
36 37
    is_scalar,
    is_vec,
38 39 40
    supports_inplace,
    supports_no_need_buffer,
)
41 42

file_loader = FileSystemLoader(Path(__file__).parent / "templates")
43 44 45 46 47 48 49 50
env = Environment(
    loader=file_loader,
    keep_trailing_newline=True,
    trim_blocks=True,
    lstrip_blocks=True,
    undefined=StrictUndefined,
    extensions=['jinja2.ext.do'],
)
51 52 53
env.filters["to_op_attr_type"] = to_op_attr_type
env.filters["to_opmaker_name"] = to_opmaker_name
env.filters["to_pascal_case"] = to_pascal_case
54 55 56
env.filters["to_scalar_tensor_name"] = to_scalar_tensor_name
env.filters["to_int_array_tensor_name"] = to_int_array_tensor_name
env.filters["to_int_array_tensors_name"] = to_int_array_tensors_name
57 58
env.filters["to_input_name"] = to_input_name
env.filters["to_opmaker_name_cstr"] = to_opmaker_name_cstr
59
env.filters["cartesian_prod_mapping"] = cartesian_prod_mapping
60
env.tests["base_op"] = is_base_op
61 62 63 64 65 66 67
env.tests["vec"] = is_vec
env.tests["scalar"] = is_scalar
env.tests["initializer_list"] = is_initializer_list
env.tests["supports_inplace"] = supports_inplace
env.tests["supports_no_need_buffer"] = supports_no_need_buffer


68 69 70 71 72
def restruct_io(op):
    op["input_dict"] = to_named_dict(op["inputs"])
    op["attr_dict"] = to_named_dict(op["attrs"])
    op["output_dict"] = to_named_dict(op["outputs"])
    return op
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
def process_scalar(op_item, scalar_configs):
    scalar_map = {
        'Scalar': 'float',
        'Scalar(float)': 'float',
        'Scalar(int)': 'int',
        'Scalar(int64_t)': 'int64_t',
    }
    if scalar_configs is not None:
        for attr_item in op_item['attrs']:
            if attr_item['name'] in scalar_configs:
                attr_type = attr_item['typename']
                assert (
                    attr_type in scalar_map
                ), f"{op_item['name']}'s scalar in op_compat.yaml is error, the data_type of {attr_item['name']} is expected to be one of Scalar, Scalar(float), Scalar(int) or Scalar(int64_t), but now is {attr_type}."

                scalar_config = scalar_configs[attr_item['name']]
                attr_item['is_support_tensor'] = (
                    True
                    if 'support_tensor' in scalar_config
                    and scalar_config['support_tensor']
                    else False
                )
                if attr_item['is_support_tensor']:
                    attr_item['typename'] = (
                        scalar_config['data_type']
                        if 'data_type' in scalar_config
                        else scalar_map[attr_type]
                    )
                else:
                    attr_item['data_type'] = (
                        scalar_config['data_type']
                        if 'data_type' in scalar_config
                        else scalar_map[attr_type]
                    )
                    attr_item['tensor_name'] = scalar_config['tensor_name']


def process_int_array(op_item, int_array_configs):
    data_type_map = {
        'int': 'std::vector<int>',
        'int64_t': 'std::vector<int64_t>',
    }
    if int_array_configs is not None:
        for attr_item in op_item['attrs']:
            if attr_item['name'] in int_array_configs:
                attr_type = attr_item['typename']
                assert (
                    attr_item['typename'] == "IntArray"
                ), f"{op_item['name']}'s int_array in op_compat.yaml is error, the data_type of {attr_item['name']} is expected to be one of IntArray, but now is {attr_type}."

                int_array_config = int_array_configs[attr_item['name']]
                attr_item['is_support_tensor'] = (
                    True
                    if 'support_tensor' in int_array_config
                    and int_array_config['support_tensor']
                    else False
                )
                if attr_item['is_support_tensor']:
                    attr_item['typename'] = (
                        data_type_map[int_array_config['data_type']]
                        if 'data_type' in int_array_config
                        else 'std::vector<int64_t>'
                    )
                else:
                    attr_item['data_type'] = (
                        data_type_map[int_array_config['data_type']]
                        if 'data_type' in int_array_config
                        else 'std::vector<int64_t>'
                    )
                    attr_item['manual_flag'] = True
                    if 'tensor_name' in int_array_config:
                        attr_item['tensor_name'] = int_array_config[
                            'tensor_name'
                        ]
                    if 'tensors_name' in int_array_config:
                        attr_item['tensors_name'] = int_array_config[
                            'tensors_name'
                        ]


155
# replace name of op and params for OpMaker
156 157 158
def replace_compat_name(op_op_map, forward_op_dict, backward_op_dict):
    def get_op_and_op_name(op_item):
        names = op_item.split('(')
159 160 161 162 163
        if len(names) == 1:
            return names[0].strip(), names[0].strip()
        else:
            return names[0].strip(), names[1].split(')')[0].strip()

164
    def update_op_attr_name(attrs, attrs_alias_map):
165 166 167 168
        for attr_item in attrs:
            if attr_item['name'] in attrs_alias_map:
                attr_item['name'] = attrs_alias_map[attr_item['name']]

169 170 171
    for op_args in op_op_map:
        new_op_name, op_name = get_op_and_op_name(op_args['op'])
        if new_op_name not in forward_op_dict:
172
            continue
173 174
        forward_op_item = forward_op_dict[new_op_name]
        has_backward = True if forward_op_item['backward'] else False
175
        if has_backward:
176 177 178
            backward_op_item = backward_op_dict[forward_op_item['backward']]
        if new_op_name != op_name:
            forward_op_item['op_name'] = op_name
179

180 181 182 183 184 185 186 187 188 189 190
        scalar_configs = None
        int_array_configs = None

        if 'scalar' in op_args:
            scalar_configs = op_args['scalar']
        if 'int_array' in op_args:
            int_array_configs = op_args['int_array']

        process_scalar(forward_op_item, scalar_configs)
        process_int_array(forward_op_item, int_array_configs)

191 192 193 194 195
        if 'backward' in op_args and has_backward:
            backward_op_list = op_args['backward'].split(',')
            _, bw_op_name = get_op_and_op_name(backward_op_list[0])
            forward_op_item['backward'] = bw_op_name
            backward_op_item['op_name'] = bw_op_name
196

197 198 199
            process_scalar(backward_op_item, scalar_configs)
            process_int_array(backward_op_item, int_array_configs)

200 201
            # for double grad
            if len(backward_op_list) > 1:
202 203 204 205 206 207
                (
                    new_double_grad_op_name,
                    double_grad_op_name,
                ) = get_op_and_op_name(backward_op_list[1])
                double_grad_item = backward_op_dict[new_double_grad_op_name]
                backward_op_item['backward'] = double_grad_op_name
208
                double_grad_item['op_name'] = double_grad_op_name
209 210 211
                if 'attrs' in op_args:
                    update_op_attr_name(
                        double_grad_item['attrs'], op_args['attrs']
212
                    )
213 214
                    update_op_attr_name(
                        double_grad_item['forward']['attrs'], op_args['attrs']
215
                    )
216

217 218 219
                process_scalar(double_grad_item, scalar_configs)
                process_int_array(double_grad_item, int_array_configs)

220 221 222
                # for triple grad
                if len(backward_op_list) > 2:
                    (
223
                        new_triple_grad_op_name,
224
                        triple_grad_op_name,
225 226
                    ) = get_op_and_op_name(backward_op_list[2])
                    triple_grad_item = backward_op_dict[new_triple_grad_op_name]
227 228
                    double_grad_item['backward'] = triple_grad_op_name
                    triple_grad_item['op_name'] = triple_grad_op_name
229 230 231
                    if 'attrs' in op_args:
                        update_op_attr_name(
                            triple_grad_item['attrs'], op_args['attrs']
232
                        )
233
                        update_op_attr_name(
234
                            triple_grad_item['forward']['attrs'],
235
                            op_args['attrs'],
236
                        )
237

238 239 240
                    process_scalar(triple_grad_item, scalar_configs)
                    process_int_array(triple_grad_item, int_array_configs)

241 242 243
        key_set = ['inputs', 'attrs', 'outputs']
        args_map = {}
        for key in key_set:
244 245 246 247 248
            if key in op_args:
                args_map.update(op_args[key])
                for args_item in forward_op_item[key]:
                    if args_item['name'] in op_args[key]:
                        args_item['name'] = op_args[key][args_item['name']]
249
                if has_backward:
250 251 252 253
                    for args_item in backward_op_item['forward'][key]:
                        if args_item['name'] in op_args[key]:
                            args_item['name'] = op_args[key][args_item['name']]
        forward_op_item['infer_meta']['param'] = [
254
            args_map[param] if param in args_map else param
255
            for param in forward_op_item['infer_meta']['param']
256
        ]
257
        forward_op_item['kernel']['param'] = [
258
            args_map[param] if param in args_map else param
259
            for param in forward_op_item['kernel']['param']
260
        ]
261 262
        if forward_op_item['kernel']['data_type']:
            forward_op_item['kernel']['data_type']['candidates'] = [
263
                args_map[param] if param in args_map else param
264
                for param in forward_op_item['kernel']['data_type'][
265 266
                    'candidates'
                ]
267
            ]
268 269
        if forward_op_item['kernel']['backend']:
            forward_op_item['kernel']['backend']['candidates'] = [
270
                args_map[param] if param in args_map else param
271
                for param in forward_op_item['kernel']['backend']['candidates']
272
            ]
273 274
        if forward_op_item['kernel']['layout']:
            forward_op_item['kernel']['layout']['candidates'] = [
275
                args_map[param] if param in args_map else param
276
                for param in forward_op_item['kernel']['layout']['candidates']
277
            ]
278
        if forward_op_item['inplace']:
279
            inplace_map = {}
280
            for key, val in forward_op_item['inplace'].items():
281 282 283 284 285
                if key in args_map:
                    key = args_map[key]
                if val in args_map:
                    val = args_map[val]
                inplace_map[key] = val
286
            forward_op_item['inplace'] = inplace_map
287 288

        if has_backward:
289
            for args_item in backward_op_item['inputs']:
290 291
                if args_item['name'] in args_map:
                    args_item['name'] = args_map[args_item['name']]
292 293 294 295 296 297 298
                elif (
                    args_item['name'].endswith('_grad')
                    and args_item['name'][:-5] in args_map
                ):
                    args_map[args_item['name']] = (
                        args_map[args_item['name'][:-5]] + '_grad'
                    )
299
                    args_item['name'] = args_map[args_item['name']]
300
            for args_item in backward_op_item['attrs']:
301 302
                if args_item['name'] in args_map:
                    args_item['name'] = args_map[args_item['name']]
303
            for args_item in backward_op_item['outputs']:
304 305 306 307 308 309 310
                if (
                    args_item['name'].endswith('_grad')
                    and args_item['name'][:-5] in args_map
                ):
                    args_map[args_item['name']] = (
                        args_map[args_item['name'][:-5]] + '_grad'
                    )
311 312
                    args_item['name'] = args_map[args_item['name']]

313 314
            if 'invoke' in backward_op_item:
                backward_op_item['invoke']['args'] = [
315
                    args_map[param.strip()]
316 317
                    if param.strip() in args_map
                    else param.strip()
318
                    for param in backward_op_item['invoke']['args'].split(',')
319 320 321
                ]
                continue

322
            backward_op_item['infer_meta']['param'] = [
323
                args_map[param] if param in args_map else param
324
                for param in backward_op_item['infer_meta']['param']
325
            ]
326
            backward_op_item['kernel']['param'] = [
327
                args_map[param] if param in args_map else param
328
                for param in backward_op_item['kernel']['param']
329
            ]
330 331
            if backward_op_item['kernel']['data_type']:
                backward_op_item['kernel']['data_type']['candidates'] = [
332
                    args_map[param] if param in args_map else param
333
                    for param in backward_op_item['kernel']['data_type'][
334 335
                        'candidates'
                    ]
336
                ]
337 338
            if backward_op_item['kernel']['backend']:
                backward_op_item['kernel']['backend']['candidates'] = [
339
                    args_map[param] if param in args_map else param
340
                    for param in backward_op_item['kernel']['backend'][
341 342
                        'candidates'
                    ]
343
                ]
344 345
            if backward_op_item['kernel']['layout']:
                backward_op_item['kernel']['layout']['candidates'] = [
346
                    args_map[param] if param in args_map else param
347
                    for param in backward_op_item['kernel']['layout'][
348 349
                        'candidates'
                    ]
350
                ]
351 352
            if backward_op_item['no_need_buffer']:
                backward_op_item['no_need_buffer'] = [
353
                    args_map[param] if param in args_map else param
354
                    for param in backward_op_item['no_need_buffer']
355
                ]
356
            if backward_op_item['inplace']:
357
                inplace_map = {}
358
                for key, val in backward_op_item['inplace'].items():
359 360 361 362 363
                    if key in args_map:
                        key = args_map[key]
                    if val in args_map:
                        val = args_map[val]
                    inplace_map[key] = val
364
                backward_op_item['inplace'] = inplace_map
365

366

367 368 369 370 371
def process_invoke_op(forward_op_dict, backward_op_dict):
    for bw_op in backward_op_dict.values():
        if 'invoke' in bw_op:
            invoke_op = bw_op['invoke']['func']
            args_list = bw_op['invoke']['args']
372
            args_index = 0
373 374 375 376 377
            if invoke_op in forward_op_dict:
                reuse_op = forward_op_dict[invoke_op]
                bw_op['invoke']['inputs'] = []
                bw_op['invoke']['attrs'] = []
                bw_op['invoke']['outputs'] = []
378
                for input_item in reuse_op['inputs']:
379
                    bw_op['invoke']['inputs'].append(
380 381 382 383 384
                        {
                            'name': input_item['name'],
                            'value': args_list[args_index],
                        }
                    )
385 386 387
                    args_index = args_index + 1
                for attr in reuse_op['attrs']:
                    if args_index < len(args_list):
388 389
                        attr_value = (
                            f"this->GetAttr(\"{args_list[args_index]}\")"
390
                            if args_list[args_index] in bw_op['attr_dict']
391 392
                            else args_list[args_index]
                        )
393
                        bw_op['invoke']['attrs'].append(
394 395
                            {'name': attr['name'], 'value': attr_value}
                        )
396 397 398 399
                        args_index = args_index + 1
                    else:
                        break
                for idx, output_item in enumerate(reuse_op['outputs']):
400
                    bw_op['invoke']['outputs'].append(
401 402
                        {
                            'name': output_item['name'],
403
                            'value': bw_op['outputs'][idx]['name'],
404 405 406 407 408 409 410 411 412 413 414 415
                        }
                    )


def main(
    ops_yaml_path,
    backward_yaml_path,
    op_compat_yaml_path,
    op_version_yaml_path,
    output_op_path,
    output_arg_map_path,
):
416
    with open(ops_yaml_path, "rt") as f:
417 418 419
        ops = yaml.safe_load(f)
        ops = [restruct_io(op) for op in ops]
    forward_op_dict = to_named_dict(ops)
420 421

    with open(backward_yaml_path, "rt") as f:
422 423 424
        backward_ops = yaml.safe_load(f)
        backward_ops = [restruct_io(op) for op in backward_ops]
    backward_op_dict = to_named_dict(backward_ops)
425 426

    with open(op_version_yaml_path, "rt") as f:
427 428 429 430
        op_versions = yaml.safe_load(f)
    # add op version info into op
    for op_version in op_versions:
        forward_op_dict[op_version['op']]['version'] = op_version['version']
431 432

    with open(op_compat_yaml_path, "rt") as f:
433
        op_op_map = yaml.safe_load(f)
434

435 436 437 438
    for op in ops:
        op['op_name'] = op['name']
    for bw_op in backward_ops:
        bw_op['op_name'] = bw_op['name']
439

440
    replace_compat_name(op_op_map, forward_op_dict, backward_op_dict)
441 442

    # prepare for invoke case
443
    process_invoke_op(forward_op_dict, backward_op_dict)
444

445 446 447 448 449 450 451
    # fill backward field for an op if another op claims it as forward
    for name, backward_op in backward_op_dict.items():
        forward_name = backward_op["forward"]["name"]
        if forward_name in backward_op_dict:
            forward_op = backward_op_dict[forward_name]
            if forward_op["backward"] is None:
                forward_op["backward"] = name
452

453 454 455
    op_dict = {}
    op_dict.update(forward_op_dict)
    op_dict.update(backward_op_dict)
456

457
    if len(ops) == 0 and len(backward_ops) == 0:
458 459 460 461 462 463 464 465
        if os.path.isfile(output_op_path):
            os.remove(output_op_path)
        if os.path.isfile(output_arg_map_path):
            os.remove(output_arg_map_path)
        return

    op_template = env.get_template('op.c.j2')
    with open(output_op_path, "wt") as f:
466
        msg = op_template.render(
467
            ops=ops, backward_ops=backward_ops, op_dict=op_dict
468
        )
469 470 471 472
        f.write(msg)

    ks_template = env.get_template('ks.c.j2')
    with open(output_arg_map_path, 'wt') as f:
473
        msg = ks_template.render(ops=ops, backward_ops=backward_ops)
474 475 476 477 478
        f.write(msg)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
479
        description="Generate operator file from op yaml."
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    )
    parser.add_argument(
        '--ops_yaml_path', type=str, help="parsed ops yaml file."
    )
    parser.add_argument(
        '--backward_yaml_path', type=str, help="parsed backward ops yaml file."
    )
    parser.add_argument(
        '--op_compat_yaml_path', type=str, help="ops args compat yaml file."
    )
    parser.add_argument(
        '--op_version_yaml_path', type=str, help="ops version yaml file."
    )
    parser.add_argument(
        "--output_op_path", type=str, help="path to save generated operators."
    )
496 497 498
    parser.add_argument(
        "--output_arg_map_path",
        type=str,
499 500
        help="path to save generated argument mapping functions.",
    )
501 502

    args = parser.parse_args()
503 504 505 506 507 508 509 510
    main(
        args.ops_yaml_path,
        args.backward_yaml_path,
        args.op_compat_yaml_path,
        args.op_version_yaml_path,
        args.output_op_path,
        args.output_arg_map_path,
    )