test_generator.py 7.1 KB
Newer Older
G
add  
gongweibao 已提交
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
# Copyright (c) 2018 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.

from __future__ import print_function
import re
import functools
import warnings
import string

from six.moves import cStringIO
from paddle.fluid.proto import framework_pb2
from paddle.fluid.framework import OpProtoHolder, Variable
from paddle.fluid.layer_helper import LayerHelper

G
add  
gongweibao 已提交
26 27
g_filer_attrs = ['op_role', 'op_role_var', 'op_namescope', 'dtype']

G
add  
gongweibao 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

def _convert_(name):
    """
    Formatting.

    Args:
       name: The name/alias

    This function takes in a name and converts it to a standard format of
    group1_group2. Where as per the regular expression, group1 can have
    alphabets and numbers and group2 has capital alphabets.

    """
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()


def _get_inputs(op_type):
    op_proto = OpProtoHolder.instance().get_op_proto(op_type)
    inputs = dict()
    for ipt in op_proto.inputs:
        inputs[ipt.name] = ""

G
add  
gongweibao 已提交
51 52
    return inputs

G
add  
gongweibao 已提交
53 54 55 56 57 58 59

def _get_outputs(op_type):
    op_proto = OpProtoHolder.instance().get_op_proto(op_type)
    outputs = {}
    for ipt in op_proto.outputs:
        outputs[ipt.name] = ""

G
add  
gongweibao 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    return outputs


def _get_attrs(op_type):
    op_proto = OpProtoHolder.instance().get_op_proto(op_type)
    return op_proto.attrs


def get_indent_space(indent, space_num=4):
    ret = ""
    for i in range(0, indent * space_num):
        ret += " "

    return ret


def get_input_comments(op_type, indent=2):
    ret = ""
    inputs = _get_inputs(op_type)
    for t in inputs:
        ret += get_indent_space(2) + "input(${%s_type}): ${%s_comment}\n" % (
            _convert_(t), _convert_(t))
G
add  
gongweibao 已提交
82

G
add  
gongweibao 已提交
83 84 85 86 87
    for t in _get_attrs(op_type):
        if t.name in g_filer_attrs:
            continue
        ret += get_indent_space(2) + "input(${%s_type}): ${%s_comment}\n" % (
            _convert_(t.name), _convert_(t.name))
G
add  
gongweibao 已提交
88

G
add  
gongweibao 已提交
89
    return ret
G
add  
gongweibao 已提交
90

G
add  
gongweibao 已提交
91 92 93 94 95 96 97

def get_output_comments(op_type, indent=2):
    ret = ""
    for t in _get_outputs(op_type):
        ret += get_indent_space(2) + "output(${%s_type}): ${%s_comment}\n" % (
            _convert_(t), _convert_(t))
    return ret
G
add  
gongweibao 已提交
98 99 100


def get_func_args(op_type):
G
add  
gongweibao 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    ret = ""
    inputs = _get_inputs(op_type)
    for t in inputs:
        ret += "%s," % _convert_(t)

    for t in _get_attrs(op_type):
        if t.name in g_filer_attrs:
            continue

        default = re.findall("\(.+\, default (.+)\(?\)", t.comment)
        if len(default) > 0:
            #print(default[0])
            ret += "{}={},".format(_convert_(t.name), default[0])
            continue

        ret += "%s=," % _convert_(t.name)

    return ret.strip(',')
G
add  
gongweibao 已提交
119 120 121


def get_inputs(op_type):
G
add  
gongweibao 已提交
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
    ret = "inputs={"
    inputs = _get_inputs(op_type)
    for t in inputs:
        ret += "{}={},".format(t, _convert_(t))
    ret = ret.strip(",")
    ret += "}"

    if ret == "inputs={}":
        return ""

    return ret


"""
def get_input_dtype(op_type):
    dtype = None
    for ipt in _get_inputs():
        name = _convert_(ipt.name)
        val = kwargs.pop(name, [])
        if not isinstance(val, list) and not isinstance(val, tuple):
            val = [val]
        if len(val) == 0:
            val = [args[0]]
            args = args[1:]

        for each in val:
            if not isinstance(each, Variable):
                raise ValueError("input of {0} must be variable".format(
                    op_type))

            if dtype is None:
                dtype = each.dtype
            elif dtype != each.dtype:
                raise ValueError(
                    "operator {0} must input same dtype. {1} vs {2}".format(
                        op_type, dtype, each.dtype))

        return dtype
"""
G
add  
gongweibao 已提交
161 162 163


def get_outputs(op_type):
G
add  
gongweibao 已提交
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
    ret = "outputs={"
    inputs = _get_outputs(op_type)
    for t in inputs:
        ret += "{}={},".format(t, _convert_(t))
    ret = ret.strip(",")
    ret += "}"

    if ret == "inputs={}":
        return ""

    return ret


"""
    attr_names = sorted(op.attr_names)
    attrs_str = ""
    for i in range(0, len(attr_names)):
        name = attr_names[i]

        attr_type = op.desc.attr_type(name)
        if attr_type == core.AttrType.BLOCK:
            a = "{name} = block[{value}]".format(
                name=name, type=attr_type, value=op.block_attr_id(name))
            attrs_str += a
            if i != len(attr_names) - 1:
                attrs_str += ", "
            continue

        if attr_type == core.AttrType.BLOCKS:
            a = "{name} = blocks{value}".format(
                name=name, type=attr_type, value=op.blocks_attr_ids(name))
            attrs_str += a
            if i != len(attr_names) - 1:
                attrs_str += ", "
            continue

        a = "{name} = {value}".format(
            name=name, type=attr_type, value=op.desc.attr(name))
        attrs_str += a
        if i != len(attr_names) - 1:
            attrs_str += ", "
"""


def get_attrs(op_type):
    ret = "attrs={"
    for t in _get_attrs(op_type):
        if t.name in g_filer_attrs:
            continue

        ret += "%s=%s," % (t.name, _convert_(t.name))

    ret = ret.strip(",")
    ret += "}"

    return ret


def get_outvars(op_type, indent=1):
    ret = ""
    for t in _get_outputs(op_type):
        ret += get_indent_space(
            indent
        ) + "%s = helper.create_tmp_variable(dtype=helper.input_dtype())\n" % (
            _convert_(t))
    ret = ret.strip('\n')
    return ret
G
add  
gongweibao 已提交
231 232 233 234 235 236 237 238


def get_op_py(op_type):
    input_comments = get_input_comments(op_type)
    output_comments = get_output_comments(op_type)
    args = get_func_args(op_type)
    inputs = get_inputs(op_type)
    outputs = get_outputs(op_type)
G
add  
gongweibao 已提交
239 240
    attrs = get_attrs(op_type)
    out_vars = get_outvars(op_type)
G
add  
gongweibao 已提交
241 242

    code = """
G
add  
gongweibao 已提交
243
@templatedoc()
G
add  
gongweibao 已提交
244 245 246 247
def {op_type}({args}):
    \"\"\"
    {op_type}
    
G
add  
gongweibao 已提交
248 249
    {comment}
    
G
add  
gongweibao 已提交
250
    Args:
G
add  
gongweibao 已提交
251
{input_comments}
G
add  
gongweibao 已提交
252
    Returns:
G
add  
gongweibao 已提交
253
{output_comments}
G
add  
gongweibao 已提交
254
    \"\"\"
G
add  
gongweibao 已提交
255 256 257
    
    helper = LayerHelper('{op_type}', **locals())
{generated_outvar}
G
add  
gongweibao 已提交
258 259 260
    helper.append_op(
        type='{op_type}',
        {inputs},
G
add  
gongweibao 已提交
261 262 263 264
        {outputs},
        {attrs})    
    
    return out
G
add  
gongweibao 已提交
265
""".format(
G
add  
gongweibao 已提交
266 267
        comment="${comment}",
        input_comments=input_comments.strip('\n'),
G
add  
gongweibao 已提交
268 269
        output_comments=output_comments,
        args=args,
G
add  
gongweibao 已提交
270
        generated_outvar=out_vars,
G
add  
gongweibao 已提交
271 272
        op_type=op_type,
        inputs=inputs,
G
add  
gongweibao 已提交
273 274
        outputs=outputs,
        attrs=attrs)
G
add  
gongweibao 已提交
275 276 277 278 279

    return code


print(get_op_py("uniform_random_batch_size_like"))
G
add  
gongweibao 已提交
280 281 282 283 284 285
#print(get_op_py("gaussian_random"))
#print(get_op_py("sampling_id"))
#print(get_op_py("gaussian_random_batch_size_like"))
#print(get_op_py("sum"))
#print(get_op_py("slice"))
#print(get_op_py("shape"))
G
add  
gongweibao 已提交
286
#get_meta("linear_chain_crf")