layer_function_generator.py 9.0 KB
Newer Older
1
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
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
D
dzhwinter 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
9 10 11 12 13
# 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.
D
dzhwinter 已提交
14 15 16
import re
import cStringIO
import functools
17
import warnings
Y
yuyang18 已提交
18
import string
D
dzhwinter 已提交
19

20
from ..proto import framework_pb2
21 22
from ..framework import OpProtoHolder, Variable
from ..layer_helper import LayerHelper
D
dzhwinter 已提交
23

Y
yuyang18 已提交
24
__all__ = ['deprecated', 'generate_layer_fn', 'autodoc', 'templatedoc']
D
dzhwinter 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42


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()


Y
yuyang18 已提交
43 44 45 46
def _type_to_str_(tp):
    return framework_pb2.AttrType.Name(tp)


D
dzhwinter 已提交
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
def _generate_doc_string_(op_proto):
    """
    Generate docstring by OpProto

    Args:
        op_proto (framework_pb2.OpProto): a protobuf message typed OpProto

    Returns:
        str: the document string
    """

    if not isinstance(op_proto, framework_pb2.OpProto):
        raise TypeError("OpProto should be `framework_pb2.OpProto`")

    buf = cStringIO.StringIO()
    buf.write(op_proto.comment)
    buf.write('\nArgs:\n')
    for each_input in op_proto.inputs:
        line_begin = '    {0}: '.format(_convert_(each_input.name))
        buf.write(line_begin)
        buf.write(each_input.comment)
        buf.write('\n')
        buf.write(' ' * len(line_begin))
        buf.write('Duplicable: ')
        buf.write(str(each_input.duplicable))
        buf.write('  Optional: ')
        buf.write(str(each_input.dispensable))
        buf.write('\n')

76 77
    skip_attrs = OpProtoHolder.generated_op_attr_names()

D
dzhwinter 已提交
78
    for each_attr in op_proto.attrs:
79 80
        if each_attr.name in skip_attrs:
            continue
D
dzhwinter 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
        buf.write('    ')
        buf.write(each_attr.name)
        buf.write(' (')
        buf.write(_type_to_str_(each_attr.type))
        buf.write('): ')
        buf.write(each_attr.comment)
        buf.write('\n')

    if len(op_proto.outputs) != 0:
        buf.write('\nReturns:\n')
        buf.write('    ')
        for each_opt in op_proto.outputs:
            if not each_opt.intermediate:
                break
        buf.write(each_opt.comment)

    return buf.getvalue()


100
def generate_layer_fn(op_type):
101
    """Register the Python layer for an Operator.
D
dzhwinter 已提交
102 103

    Args:
104
       op_type: The name of the operator to be created.
D
dzhwinter 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117

    This function takes in the operator type (sigmoid, mean , average etc) and
    creates the operator functionality.

    """
    op_proto = OpProtoHolder.instance().get_op_proto(op_type)
    not_intermediate_outputs = \
        filter(lambda output: not output.intermediate, op_proto.outputs)
    intermediate_outputs = \
        filter(lambda output: output.intermediate, op_proto.outputs)

    if len(not_intermediate_outputs) != 1:
        raise ValueError("Only one non intermediate output operator can be",
Y
yuyang18 已提交
118
                         "automatically generated. {0}".format(op_type))
D
dzhwinter 已提交
119 120 121

    if not_intermediate_outputs[0].duplicable:
        raise ValueError(
122
            "Only non duplicable op can be automatically generated.")
D
dzhwinter 已提交
123 124 125 126

    for output in intermediate_outputs:
        if output.duplicable:
            raise ValueError("The op can be automatically generated only when ",
127
                             "all intermediate ops are not duplicable.")
D
dzhwinter 已提交
128 129 130 131

    o_name = not_intermediate_outputs[0].name
    intermediate_output_names = [output.name for output in intermediate_outputs]

Y
Yu Yang 已提交
132
    def infer_and_check_dtype(op_proto, *args, **kwargs):
D
dzhwinter 已提交
133 134 135 136 137 138 139 140 141 142
        """
        This function performs the sanity check for dtype and
        instance type.
        """
        dtype = None
        for ipt in op_proto.inputs:
            name = _convert_(ipt.name)
            val = kwargs.pop(name, [])
            if not isinstance(val, list) and not isinstance(val, tuple):
                val = [val]
Y
Yu Yang 已提交
143 144 145 146
            if len(val) == 0:
                val = [args[0]]
                args = args[1:]

D
dzhwinter 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160
            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

Y
Yu Yang 已提交
161
    def func(*args, **kwargs):
D
dzhwinter 已提交
162 163
        helper = LayerHelper(op_type, **kwargs)

Y
Yu Yang 已提交
164
        dtype = infer_and_check_dtype(op_proto, *args, **kwargs)
D
dzhwinter 已提交
165 166 167 168 169 170 171

        inputs = dict()
        for ipt in op_proto.inputs:
            name = _convert_(ipt.name)
            val = kwargs.pop(name, [])
            if not isinstance(val, list) and not isinstance(val, tuple):
                val = [val]
Y
Yu Yang 已提交
172 173 174
            if len(val) == 0 and len(args) != 0:
                val = args[0]
                args = args[1:]
D
dzhwinter 已提交
175 176 177
            inputs[ipt.name] = val

        outputs = dict()
178 179 180 181 182 183 184
        out = kwargs.pop(_convert_(o_name), [])
        if out:
            out_var = out[0] if (isinstance(out, list) or
                                 isinstance(out, tuple)) else out
        else:
            out_var = helper.create_tmp_variable(dtype=dtype)
        outputs[o_name] = [out_var]
D
dzhwinter 已提交
185 186 187 188
        for name in intermediate_output_names:
            outputs[name] = [helper.create_tmp_variable(dtype=dtype)]
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=kwargs)
189
        return helper.append_activation(out_var)
D
dzhwinter 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

    func.__name__ = op_type
    func.__doc__ = _generate_doc_string_(op_proto)
    return func


def deprecated(func_or_class):
    """
    Deprecated warning decorator. It will result a warning message.
    Should be used before class or function, member function
    """

    @functools.wraps(func)
    def func_wrapper(*args, **kwargs):
        """
        Wrap func with deprecated warning
        """
Y
Yang Yu 已提交
207
        warnings.simplefilter('always', DeprecationWarning)  # turn off filter
D
dzhwinter 已提交
208 209 210 211
        warnings.warn(
            "Call to deprecated function {}.".format(func.__name__),
            category=DeprecationWarning,
            stacklevel=2)
Y
Yang Yu 已提交
212
        warnings.simplefilter('default', DeprecationWarning)  # reset filter
D
dzhwinter 已提交
213 214 215
        return func(*args, **kwargs)

    return func_wrapper
Y
Yang Yu 已提交
216 217


218 219 220 221 222 223 224
def autodoc(comment=""):
    def __impl__(func):
        func.__doc__ = _generate_doc_string_(OpProtoHolder.instance(
        ).get_op_proto(func.__name__)) + comment
        return func

    return __impl__
Y
yuyang18 已提交
225 226


Y
yuyang18 已提交
227
def templatedoc(op_type=None):
Y
yuyang18 已提交
228 229 230 231 232 233 234 235 236 237
    """
    Decorator of layer function. It will use the docstring from the layer
    function as the template. The template arguments are:

    * ${comment}: The operator comment written in CPP.
    * ${{name}_comment}: The comment of ${name} written with AddAttr, AddOutput,
        and AddInput. The ${name} is Python snake style. i.e., xxx_xxx.
    * ${{name}_type}: The type of ${name}.

    Returns:
Y
yuyang18 已提交
238
        Decorated function.
Y
yuyang18 已提交
239 240
    """

Y
yuyang18 已提交
241 242 243
    def trim_ending_dot(msg):
        return msg.rstrip('.')

Y
yuyang18 已提交
244
    def __impl__(func):
Y
yuyang18 已提交
245 246 247 248 249
        if op_type is None:
            op_type_name = func.__name__
        else:
            op_type_name = op_type
        op_proto = OpProtoHolder.instance().get_op_proto(op_type_name)
Y
yuyang18 已提交
250
        tmpl = string.Template(func.__doc__)
Y
yuyang18 已提交
251 252 253 254

        comment_lines = op_proto.comment.split("\n")
        comment = ""
        for line in comment_lines:
Y
yuyang18 已提交
255 256 257 258
            line = line.strip()
            if len(line) != 0:
                comment += line
                comment += " "
Y
yuyang18 已提交
259

Y
yuyang18 已提交
260
        args = {"comment": trim_ending_dot(comment)}
Y
yuyang18 已提交
261 262
        for each_input in op_proto.inputs:
            input_name = _convert_(each_input.name)
Y
yuyang18 已提交
263 264
            args["{0}_comment".format(input_name)] = trim_ending_dot(
                each_input.comment)
Y
yuyang18 已提交
265 266 267
            args["{0}_type".format(input_name)] = "Variable"
        for each_attr in op_proto.attrs:
            input_name = _convert_(each_attr.name)
Y
yuyang18 已提交
268 269
            args["{0}_comment".format(input_name)] = trim_ending_dot(
                each_attr.comment)
Y
yuyang18 已提交
270 271 272 273
            args["{0}_type".format(input_name)] = _type_to_str_(each_attr.type)

        for each_opt in op_proto.outputs:
            output_name = _convert_(each_opt.name)
Y
yuyang18 已提交
274 275
            args["{0}_comment".format(output_name)] = trim_ending_dot(
                each_opt.comment)
Y
yuyang18 已提交
276 277 278 279 280
            args["{0}_type".format(output_name)] = "Variable"
        func.__doc__ = tmpl.substitute(args)
        return func

    return __impl__