parse_utils.py 22.8 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
# 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
from copy import copy
17 18
from typing import Any, Dict, List, Tuple

C
Charles-hit 已提交
19
from tests_utils import is_attr, is_input, is_output, is_vec
20
from type_mapping import opmaker_attr_types_map
21 22


23
def to_named_dict(items: List[Dict], is_op=False) -> Dict[str, Dict]:
24
    named_dict = {}
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
    if is_op:
        for item in items:
            if "name" not in item:
                raise KeyError(f"name not in {item}")
            item["name"] = (
                item["name"] if item["name"][-1] != '_' else item["name"][:-1]
            )
            name = item["name"]
            named_dict[name] = item
    else:
        for item in items:
            if "name" not in item:
                raise KeyError(f"name not in {item}")
            name = item["name"]
            named_dict[name] = item
40 41 42
    return named_dict


43
def parse_arg(op_name: str, s: str) -> Dict[str, str]:
44 45 46 47
    """parse an argument in following formats:
    1. typename name
    2. typename name = default_value
    """
48
    typename, rest = (item.strip() for item in s.split(" ", 1))
49 50
    assert (
        len(typename) > 0
51
    ), f"The arg typename should not be empty. Please check the args of {op_name} in yaml."
52

53 54
    assert (
        rest.count("=") <= 1
55
    ), f"There is more than 1 = in an arg in {op_name}"
56
    if rest.count("=") == 1:
57
        name, default_value = (item.strip() for item in rest.split("=", 1))
58 59
        assert (
            len(name) > 0
60
        ), f"The arg name should not be empty. Please check the args of {op_name} in yaml."
61 62
        assert (
            len(default_value) > 0
63
        ), f"The default value should not be empty. Please check the args of {op_name} in yaml."
64 65 66
        return {
            "typename": typename,
            "name": name,
67
            "default_value": default_value,
68 69 70
        }
    else:
        name = rest.strip()
71 72
        assert (
            len(name) > 0
73
        ), f"The arg name should not be empty. Please check the args of {op_name} in yaml."
74 75 76
        return {"typename": typename, "name": name}


77
def parse_input_and_attr(
78
    op_name: str, arguments: str
79
) -> Tuple[List, List, Dict, Dict]:
80
    args_str = arguments.strip()
81 82
    assert args_str.startswith('(') and args_str.endswith(')'), (
        f"Args declaration should start with '(' and end with ')', "
83
        f"please check the args of {op_name} in yaml."
84
    )
85 86 87 88 89 90 91 92 93
    args_str = args_str[1:-1]
    args = parse_plain_list(args_str)

    inputs = []
    attrs = []

    met_attr_with_default_value = False

    for arg in args:
94
        item = parse_arg(op_name, arg)
95 96 97
        typename = item["typename"]
        name = item["name"]
        if is_input(typename):
98 99
            assert len(attrs) == 0, (
                f"The input Tensor should appear before attributes. "
100
                f"please check the position of {op_name}:input({name}) "
101 102
                f"in yaml."
            )
103 104 105
            inputs.append(item)
        elif is_attr(typename):
            if met_attr_with_default_value:
106 107
                assert (
                    "default_value" in item
108
                ), f"{op_name}: Arguments with default value should not precede those without default value"
109 110
            elif "default_value" in item:
                met_attr_with_default_value = True
111 112
            if typename.startswith('Scalar') or typename == 'IntArray':
                item['data_type'] = opmaker_attr_types_map[typename]
113 114
            attrs.append(item)
        else:
115
            raise KeyError(f"{op_name}: Invalid argument type {typename}.")
116 117 118
    return inputs, attrs


119
def parse_output(op_name: str, s: str) -> Dict[str, str]:
120 121 122
    """parse an output, typename or typename(name)."""
    match = re.search(
        r"(?P<out_type>[a-zA-Z0-9_[\]]+)\s*(?P<name>\([a-zA-Z0-9_@]+\))?\s*(?P<expr>\{[^\}]+\})?",
123 124
        s,
    )
125 126 127 128 129 130 131
    typename = match.group("out_type")
    name = match.group("name")
    size_expr = match.group("expr")

    name = name[1:-1] if name is not None else 'out'
    size_expr = size_expr[1:-1] if size_expr is not None else None

132
    assert is_output(typename), (
133
        f"Invalid output type: {typename} in op : {op_name}."
134 135
        f"Supported types are Tensor and Tensor[]"
    )
136
    if size_expr is not None:
137
        assert is_vec(typename), (
138
            f"Invalid output size: output {name} in op : {op_name} is "
139 140
            f"not a vector but has size expr"
        )
141 142 143 144 145
        return {"typename": typename, "name": name, "size": size_expr}
    else:
        return {"typename": typename, "name": name}


146
def parse_outputs(op_name: str, outputs: str) -> List[Dict]:
147 148 149
    outputs = parse_plain_list(outputs, sep=",")
    output_items = []
    for output in outputs:
150
        output_items.append(parse_output(op_name, output))
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    return output_items


def parse_infer_meta(infer_meta: Dict[str, Any]) -> Dict[str, Any]:
    infer_meta = copy(infer_meta)  # to prevent mutating the input
    if "param" not in infer_meta:
        infer_meta["param"] = None
    return infer_meta


def parse_candidates(s: str) -> Dict[str, Any]:
    "parse candidates joined by either '>'(ordered) or ','(unordered)"
    delimiter = ">" if ">" in s else ","
    ordered = delimiter == ">"
    candidates = parse_plain_list(s, delimiter)
    return {"ordered": ordered, "candidates": candidates}


def parse_plain_list(s: str, sep=",") -> List[str]:
170 171 172 173 174 175 176
    if sep == ",":
        patten = re.compile(r',(?![^{]*\})')  # support "int[] a={1,2}"
        items = re.split(patten, s.strip())
        items = [x.strip() for x in items]
        return items
    else:
        return [item.strip() for item in s.strip().split(sep)]
177 178


179
def parse_kernel(op_name: str, kernel_config: Dict[str, Any]) -> Dict[str, Any]:
180 181 182 183 184 185
    # kernel :
    #    func : [], Kernel functions (example: scale, scale_sr)
    #    param : [], Input params of kernel
    #    backend : str, the names of param to choose the kernel backend, default is None
    #    layout : str, the names of param to choose the kernel layout, default is None
    #    data_type : str, the names of param to choose the kernel data_type, default is None
186
    #    dispatch : {}, the key is kernel_func, the value is type of inputs and outputs for kernel (example: {kernel_name : (['dense','sparse_coo']#input,['sparse_coo']#output)})
187
    kernel = {
188
        'func': [],  # up to 2 function names
189 190 191
        'param': None,
        'backend': None,
        'layout': None,
192
        'data_type': None,
193
        'dispatch': {},
194
        'force_backend': None,
195 196 197 198
    }
    if 'param' in kernel_config:
        kernel['param'] = kernel_config['param']

199 200 201
    if 'force_backend' in kernel_config:
        kernel['force_backend'] = kernel_config["force_backend"]

202 203 204 205 206 207 208
    if 'backend' in kernel_config:
        kernel['backend'] = parse_candidates(kernel_config["backend"])

    if 'layout' in kernel_config:
        kernel['layout'] = parse_candidates(kernel_config["layout"])

    if 'data_type' in kernel_config:
209 210 211 212 213 214 215 216 217 218 219 220 221 222
        data_type_item = parse_candidates(kernel_config["data_type"])
        params_num = len(data_type_item['candidates'])
        data_type_item['to_complex_flag'] = [False] * params_num
        for i in range(params_num):
            complex_match_result = re.match(
                r"complex\((?P<param_name>\w+)\)",
                data_type_item['candidates'][i],
            )
            if complex_match_result:
                data_type_item['candidates'][i] = complex_match_result.group(
                    'param_name'
                )
                data_type_item['to_complex_flag'][i] = True
        kernel['data_type'] = data_type_item
223 224

    kernel_funcs = re.compile(r'([a-zA-Z0-9_]+)\s*({[^}]+})?').findall(
225 226
        kernel_config['func']
    )
227 228 229 230 231 232 233 234 235 236 237

    def parse_kernel_in_out_type(in_out_str):
        if len(in_out_str) == 0:
            return None
        tmp_in_out_list = in_out_str[1:-1].split('->')
        inputs = [item.strip() for item in tmp_in_out_list[0].split(',')]
        outputs = [item.strip() for item in tmp_in_out_list[1].split(',')]

        # check the tensor type
        for item in inputs:
            assert item in [
238 239 240 241
                'dense',
                'selected_rows',
                'sparse_coo',
                'sparse_csr',
242
            ], f"{op_name} : Invalid input tensor type ('{item}'), here we only support 'dense', 'selected_rows', 'sparse_coo' and 'sparse_csr'."
243 244
        for item in outputs:
            assert item in [
245 246 247 248
                'dense',
                'selected_rows',
                'sparse_coo',
                'sparse_csr',
249
            ], f"{op_name} : Invalid output tensor type ('{item}'), here we only support 'dense', 'selected_rows', 'sparse_coo' and 'sparse_csr'."
250 251 252 253 254 255

        return (inputs, outputs)

    for func_item in kernel_funcs:
        kernel['func'].append(func_item[0])
        kernel['dispatch'][func_item[0]] = parse_kernel_in_out_type(
256 257
            func_item[1]
        )
258

259 260 261
    return kernel


262
def parse_inplace(op_name: str, inplace_cfg: str) -> Dict[str, str]:
263 264 265 266 267 268 269 270 271
    inplace_map = {}
    inplace_cfg = inplace_cfg.lstrip("(").rstrip(")")
    pairs = parse_plain_list(inplace_cfg)
    for pair in pairs:
        in_name, out_name = parse_plain_list(pair, sep="->")
        inplace_map[out_name] = in_name
    return inplace_map


272
def parse_invoke(op_name: str, invoke_config: str) -> Dict[str, Any]:
273 274 275 276 277 278 279 280 281
    invoke_config = invoke_config.strip()
    func, rest = invoke_config.split("(", 1)
    func = func.strip()
    args = rest.rstrip(")").strip()
    invocation = {"func": func, "args": args}
    return invocation


def extract_type_and_name(records: List[Dict]) -> List[Dict]:
282
    """extract type and name from forward call, it is simpler than forward op ."""
283 284 285
    extracted = [
        {"name": item["name"], "typename": item["typename"]} for item in records
    ]
286 287 288
    return extracted


289 290
def parse_forward(op_name: str, forward_config: str) -> Dict[str, Any]:
    # op_name (const Tensor& input, ... , int attr, ...) -> Tensor(out)
291
    result = re.search(
292
        r"(?P<op>[a-z][a-z0-9_]+)\s*(?P<args>\([^\)]+\))\s*->\s*(?P<outputs>.+)",
293 294
        forward_config,
    )
295 296
    op = result.group("op")
    outputs = parse_outputs(op_name, result.group("outputs"))
297 298
    outputs = extract_type_and_name(outputs)

299
    inputs, attrs = parse_input_and_attr(op_name, result.group("args"))
300 301 302
    inputs = extract_type_and_name(inputs)
    attrs = extract_type_and_name(attrs)
    forward_cfg = {
303
        "name": op,
304 305
        "inputs": inputs,
        "attrs": attrs,
306
        "outputs": outputs,
307 308 309 310
    }
    return forward_cfg


J
Jiabin Yang 已提交
311 312 313 314 315
def parse_composite(
    op_name: str,
    composite_config: str,
) -> Dict[str, Any]:
    # composite_config: func(args1, args2,.....)
316 317 318 319 320 321 322
    result = re.search(
        r"(?P<func_name>[a-z][a-z0-9_]+)\s*\((?P<func_args>[^\)]+)\)",
        composite_config,
    )

    func_name = result.group("func_name")
    func_args = result.group("func_args")
J
Jiabin Yang 已提交
323 324 325 326 327 328 329

    composite_dict = {}
    composite_dict["func_name"] = func_name
    composite_dict["func_args"] = func_args
    return composite_dict


330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
def check_op_config(op_entry, op_name):
    base_key_set = (
        'op',
        'backward_op',
        'forward',
        'args',
        'output',
        'infer_meta',
        'kernel',
        'backward',
        'invoke',
        'inplace',
        'view',
        'optional',
        'intermediate',
        'no_need_buffer',
        'data_transform',
J
Jiabin Yang 已提交
347
        'composite',
348
        'support_dygraph_mode',
349 350
    )
    infer_meta_key_set = ('func', 'param')
351 352 353 354 355 356 357 358
    kernel_key_set = (
        'func',
        'param',
        'data_type',
        'layout',
        'backend',
        'force_backend',
    )
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    for key in op_entry.keys():
        assert (
            key in base_key_set
        ), f"Op ({op_name}) : invalid key ({key}) in Yaml."

    if 'infer_meta' in op_entry:
        for infer_meta_key in op_entry['infer_meta'].keys():
            assert (
                infer_meta_key in infer_meta_key_set
            ), f"Op ({op_name}) : invalid key (infer_meta.{infer_meta_key}) in Yaml."

    if 'kernel' in op_entry:
        for kernel_key in op_entry['kernel'].keys():
            assert (
                kernel_key in kernel_key_set
            ), f"Op ({op_name}) : invalid key (kernel.{kernel_key}) in Yaml."


377 378 379 380
def parse_op_entry(op_entry: Dict[str, Any], name_field="op"):
    op_name = op_entry[name_field]
    inputs, attrs = parse_input_and_attr(op_name, op_entry["args"])
    outputs = parse_outputs(op_name, op_entry["output"])
J
Jiabin Yang 已提交
381 382
    if "composite" in op_entry:
        composite_dict = parse_composite(op_name, op_entry["composite"])
383
    check_op_config(op_entry, op_name)
384 385 386 387 388 389
    # validate default value of DataType and DataLayout
    for attr in attrs:
        if "default_value" in attr:
            typename = attr["typename"]
            default_value = attr["default_value"]
            if typename == "DataType":
390 391
                assert (
                    "DataType" in default_value
392
                ), f"invalid DataType default value in {op_name}"
393
                # remove namespace
394
                default_value = default_value[default_value.find("DataType") :]
395 396
                attr["default_value"] = default_value
            elif typename == "DataLayout":
397 398
                assert (
                    "DataLayout" in default_value
399
                ), f"invalid DataLayout default value in {op_name}"
400 401 402
                default_value = default_value[
                    default_value.find("DataLayout") :
                ]
403 404 405 406 407 408 409 410 411
                attr["default_value"] = default_value

    input_names = [item["name"] for item in inputs]
    attr_names = [item["name"] for item in attrs]
    output_names = [item["name"] for item in outputs]

    # add optional tag for every input
    for input in inputs:
        input["optional"] = False
412 413 414
    for output in outputs:
        output["optional"] = False

415 416
    if "optional" in op_entry:
        optional_args = parse_plain_list(op_entry["optional"])
417
        for name in optional_args:
418
            assert (
419 420
                name in input_names or name in output_names
            ), f"{op_name} has an optional tensor: '{name}' which is not in input or output."
421 422 423
        for input in inputs:
            if input["name"] in optional_args:
                input["optional"] = True
424 425 426
        for output in outputs:
            if output["name"] in optional_args:
                output["optional"] = True
427 428 429 430

    # add intermediate tag for every output
    for output in outputs:
        output["intermediate"] = False
431 432
    if "intermediate" in op_entry:
        intermediate_outs = parse_plain_list(op_entry["intermediate"])
433
        for name in intermediate_outs:
434 435
            assert (
                name in output_names
436
            ), f"{op_name} has an intermediate output: '{name}' which is not an output."
437 438 439 440 441 442 443
        for output in outputs:
            if output["name"] in intermediate_outs:
                output["intermediate"] = True

    # add no_need_buffer for every input
    for input in inputs:
        input["no_need_buffer"] = False
444 445
    if "no_need_buffer" in op_entry:
        no_buffer_args = parse_plain_list(op_entry["no_need_buffer"])
446
        for name in no_buffer_args:
447 448
            assert (
                name in input_names
449
            ), f"{op_name} has an no buffer input: '{name}' which is not an input."
450 451 452 453 454 455
        for input in inputs:
            if input["name"] in no_buffer_args:
                input["no_need_buffer"] = True
    else:
        no_buffer_args = None

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    # add data_transform tag for every input.
    # the format is {data_transform : {skip_transform : [x, z], support_trans_dtype : y}}
    for input in inputs:
        input["data_transform"] = {}
    if "data_transform" in op_entry:
        skip_trans_args = []
        support_trans_args = []
        data_trans = op_entry["data_transform"]
        if "skip_transform" in data_trans:
            skip_trans_args = parse_plain_list(data_trans["skip_transform"])
            for name in skip_trans_args:
                assert (
                    name in input_names
                ), f"{op_name} has an skip_transform input: '{name}' which is not an input."
            data_trans["skip_transform"] = skip_trans_args
        if "support_trans_dtype" in data_trans:
            support_trans_args = parse_plain_list(
                data_trans["support_trans_dtype"]
            )
            for name in support_trans_args:
                assert (
                    name in input_names
                ), f"{op_name} has an support_trans_dtype input: '{name}' which is not an input."
            data_trans["support_trans_dtype"] = support_trans_args
        for input in inputs:
            if input["name"] in skip_trans_args:
                input["data_transform"]["skip_trans_args"] = True
            else:
                input["data_transform"]["skip_trans_args"] = False
            if input["name"] in support_trans_args:
                input["data_transform"]["support_trans_dtype"] = True
            else:
                input["data_transform"]["support_trans_dtype"] = False
    else:
        data_trans = None
491

492 493
    op = {
        "name": op_name,
494 495 496
        "inputs": inputs,
        "attrs": attrs,
        "outputs": outputs,
497
        "no_need_buffer": no_buffer_args,
498
        "data_transform": data_trans,
499 500
    }

X
xiaoguoguo626807 已提交
501 502 503 504 505 506
    # op should be is_base_op or is_invoke_op or is_only_composite_op
    is_base_op = True
    if "invoke" in op_entry:
        is_base_op = False
    if "composite" in op_entry and "kernel" not in op_entry:
        is_base_op = False
507

508
    if is_base_op:
509
        # kernel
510
        kernel = parse_kernel(op_name, op_entry["kernel"])
511 512 513 514
        if kernel["param"] is None:
            kernel["param"] = input_names + attr_names

        # infer meta
515
        infer_meta = parse_infer_meta(op_entry["infer_meta"])
516 517 518 519
        if infer_meta["param"] is None:
            infer_meta["param"] = copy(kernel["param"])

        # inplace
520 521
        if "inplace" in op_entry:
            inplace_pairs = parse_inplace(op_name, op_entry["inplace"])
522 523
        else:
            inplace_pairs = None
524
        op.update(
525 526 527 528 529 530
            {
                "infer_meta": infer_meta,
                "kernel": kernel,
                "inplace": inplace_pairs,
            }
        )
X
xiaoguoguo626807 已提交
531 532 533 534 535

    # has invoke ?
    if "invoke" in op_entry:
        invoke_dict = parse_invoke(op_name, op_entry["invoke"])
        op.update({"invoke": invoke_dict})
536

J
Jiabin Yang 已提交
537 538 539 540
    # has composite ?
    if "composite" in op_entry:
        op.update({"composite": composite_dict})

541
    # backward
542 543
    if "backward" in op_entry:
        backward = op_entry["backward"]
544 545
    else:
        backward = None
546
    op["backward"] = backward
547

548 549 550 551 552
    # forward for backward_ops
    is_backward_op = name_field == "backward_op"
    if is_backward_op:
        if "forward" in op_entry:
            forward = parse_forward(op_name, op_entry["forward"])
553
            # validate_fb
554
            validate_backward_inputs(
555
                op_name, forward["inputs"], forward["outputs"], inputs
556
            )
557 558
            validate_backward_attrs(op_name, forward["attrs"], attrs)
            validate_backward_outputs(op_name, forward["inputs"], outputs)
559 560
        else:
            forward = None
561 562
        op["forward"] = forward
    return op
563 564


565
def validate_backward_attrs(op, forward_attrs, backward_attrs):
566 567 568
    if len(forward_attrs) >= len(backward_attrs):
        return
    num_exceptional_attrs = len(backward_attrs) - len(forward_attrs)
569 570
    # this is a not-that-clean trick to allow backward op to has more attrs
    # than the forward op , as long as they all have default value
571
    for i in range(-num_exceptional_attrs, 0):
572 573
        assert (
            "default_value" in backward_attrs[i]
574
        ), f"{op } has exceptional attr without default value"
575 576


577
def validate_backward_inputs(
578
    op, forward_inputs, forward_outputs, backward_inputs
579
):
580 581 582 583 584
    foward_input_names = [item["name"] for item in forward_inputs]
    forward_output_names = [item["name"] for item in forward_outputs]
    backward_input_names = [item["name"] for item in backward_inputs]

    assert len(backward_input_names) <= len(foward_input_names) + 2 * len(
585
        forward_output_names
586
    ), f"{op } has too many inputs."
587 588


589
def validate_backward_outputs(op, forward_inputs, backward_outputs):
590
    assert len(backward_outputs) <= len(
591
        forward_inputs
592
    ), f"{op } has too many outputs"
593 594


595 596 597 598
def cross_validate(ops):
    for name, op in ops.items():
        if "forward" in op:
            fw_call = op["forward"]
599
            fw_name = fw_call["name"]
600
            if fw_name not in ops:
601
                print(
602
                    f"Something Wrong here, this backward op ({name})'s forward op ({fw_name}) does not exist."
603 604
                )
            else:
605 606
                fw_op = ops[fw_name]
                if "backward" not in fw_op or fw_op["backward"] is None:
607
                    print(
608
                        f"Something Wrong here, {name}'s forward op ({fw_name}) does not claim {name} as its backward."
609 610
                    )
                else:
611
                    assert (
612
                        fw_op["backward"] == name
613
                    ), f"{name}: backward and forward name mismatch"
614 615

                assert len(fw_call["inputs"]) <= len(
616 617
                    fw_op["inputs"]
                ), f"{name}: forward call has more inputs than the op "
618
                for input, input_ in zip(fw_call["inputs"], fw_op["inputs"]):
619 620 621
                    assert (
                        input["typename"] == input_["typename"]
                    ), f"type mismatch in {name} and {fw_name}"
622 623

                assert len(fw_call["attrs"]) <= len(
624 625
                    fw_op["attrs"]
                ), f"{name}: forward call has more attrs than the op "
626
                for attr, attr_ in zip(fw_call["attrs"], fw_op["attrs"]):
627 628 629 630 631 632
                    if attr["typename"] == "Scalar":
                        # special case for Scalar, fw_call can omit the type
                        assert re.match(
                            r"Scalar(\(\w+\))*", attr_["typename"]
                        ), f"type mismatch in {name} and {fw_name}"
                    else:
633 634 635
                        assert (
                            attr["typename"] == attr_["typename"]
                        ), f"type mismatch in {name} and {fw_name}"
636 637

                assert len(fw_call["outputs"]) == len(
638 639
                    fw_op["outputs"]
                ), f"{name}: forward call has more outputs than the op "
640
                for output, output_ in zip(
641
                    fw_call["outputs"], fw_op["outputs"]
642 643 644 645
                ):
                    assert (
                        output["typename"] == output_["typename"]
                    ), f"type mismatch in {name} and {fw_name}"