util.py 2.0 KB
Newer Older
S
SunAhong1993 已提交
1
# Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
J
jiangjiajun 已提交
2 3 4 5 6 7 8 9 10 11 12 13
#
# 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.
J
jiangjiajun 已提交
14
import numpy
J
jiangjiajun 已提交
15 16
import math
import os
S
SunAhong1993 已提交
17
import inspect
J
jiangjiajun 已提交
18

J
jiangjiajun 已提交
19 20 21

def string(param):
    return "\'{}\'".format(param)
S
SunAhong1993 已提交
22 23 24 25 26 27 28

def name_generator(nn_name, nn_name2id):
    if nn_name in nn_name2id:
        nn_name2id[nn_name] += 1
    else:
        nn_name2id[nn_name] = 0
    real_nn_name = nn_name + str(nn_name2id[nn_name])
S
SunAhong1993 已提交
29 30
    return real_nn_name

S
SunAhong1993 已提交
31
def remove_default_attrs(kernel, attrs):
S
SunAhong1993 已提交
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
    def get_default_args(func):
        signature = inspect.signature(func)
        return {
            k: v.default
            for k, v in signature.parameters.items()
            if v.default is not inspect.Parameter.empty
        }
    is_func = True
    if "paddle.nn" in kernel and "functional"not in kernel:
        is_func = False
    import paddle
    obj = paddle
    for i, part in enumerate(kernel.split(".")):
        if i == 0:
            continue
        obj = getattr(obj, part)
    if is_func:
        func = obj
    else:
        func = obj.__init__ 
    default_attrs = get_default_args(func)
    for default_k, default_v in default_attrs.items():
        if default_k in attrs:
            if (isinstance(attrs[default_k], list) or isinstance(attrs[default_k], tuple)) \
                    and not is_func:
                if len(set(attrs[default_k])) == 1:
                    attrs[default_k] = attrs[default_k][0]
            if default_v == attrs[default_k]:
S
SunAhong1993 已提交
60
                attrs.pop(default_k)