“da0022e40393783c5ee48627e62be04f21bb9e1b”上不存在“paddle/fluid/git@gitcode.net:paddlepaddle/Paddle.git”
layer_function_generator.py 11.8 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.
14 15

from __future__ import print_function
D
dzhwinter 已提交
16 17
import re
import functools
18
import warnings
Y
yuyang18 已提交
19
import string
D
dzhwinter 已提交
20

21
from six.moves import cStringIO
22
from ..proto import framework_pb2
23
from ..framework import OpProtoHolder, Variable, core, convert_np_dtype_to_dtype_, in_dygraph_mode
24
from ..layer_helper import LayerHelper
25
from ..data_feeder import check_variable_and_dtype
D
dzhwinter 已提交
26

27
__all__ = [
28
    'generate_layer_fn', 'generate_activation_fn', 'autodoc', 'templatedoc'
29
]
D
dzhwinter 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47


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 已提交
48 49 50 51
def _type_to_str_(tp):
    return framework_pb2.AttrType.Name(tp)


52 53 54 55 56
_two_dollar_pattern_ = re.compile(r"\$\$([^\$]+)\$\$")
_single_dollar_pattern_ = re.compile(r"\$([^\$]+)\$")
_two_bang_pattern_ = re.compile(r"!!([^!]+)!!")


Y
yuyang18 已提交
57
def escape_math(text):
N
Noel 已提交
58 59 60 61 62
    #return _two_bang_pattern_.sub(
    #    r'$$\1$$',
    #    _single_dollar_pattern_.sub(r':math:\n`\1`',
    #                                _two_dollar_pattern_.sub(r"!!\1!!", text)))
    return _two_dollar_pattern_.sub(r':math:`\1`', text)
Y
yuyang18 已提交
63 64


65 66 67
def _generate_doc_string_(op_proto,
                          additional_args_lines=None,
                          skip_attrs_set=None):
D
dzhwinter 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80
    """
    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`")

81
    buf = cStringIO()
82
    buf.write(escape_math(op_proto.comment))
D
dzhwinter 已提交
83 84
    buf.write('\nArgs:\n')
    for each_input in op_proto.inputs:
85
        line_begin = '    {0}'.format(_convert_(each_input.name))
D
dzhwinter 已提交
86
        buf.write(line_begin)
87
        buf.write(" (Tensor): ")
88 89 90 91 92
        buf.write(escape_math(each_input.comment))
        if each_input.duplicable:
            buf.write("  Duplicatable.")
        if each_input.dispensable:
            buf.write("  Optional.")
D
dzhwinter 已提交
93 94
        buf.write('\n')

95
    skip_attrs = OpProtoHolder.generated_op_attr_names()
96 97 98
    # attr use_mkldnn and is_test also should not be visible to users.
    skip_attrs.add("use_mkldnn")
    skip_attrs.add("is_test")
99
    skip_attrs.add("use_cudnn")
100 101 102 103 104

    if skip_attrs_set:
        for t in skip_attrs_set:
            skip_attrs.add(t)

D
dzhwinter 已提交
105
    for each_attr in op_proto.attrs:
106 107
        if each_attr.name in skip_attrs:
            continue
D
dzhwinter 已提交
108 109 110 111 112
        buf.write('    ')
        buf.write(each_attr.name)
        buf.write(' (')
        buf.write(_type_to_str_(each_attr.type))
        buf.write('): ')
113
        buf.write(escape_math(each_attr.comment))
D
dzhwinter 已提交
114 115
        buf.write('\n')

S
sneaxiy 已提交
116 117 118 119 120 121 122
    if additional_args_lines is not None:
        for line in additional_args_lines:
            line = line.strip()
            buf.write('    ')
            buf.write(line)
            buf.write('\n')

D
dzhwinter 已提交
123 124 125 126 127 128
    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
129 130
        buf.write(_convert_(each_opt.name))
        buf.write(' (Tensor): ')
131
        buf.write(escape_math(each_opt.comment))
D
dzhwinter 已提交
132 133 134 135

    return buf.getvalue()


136
def generate_layer_fn(op_type):
137
    """Register the Python layer for an Operator.
D
dzhwinter 已提交
138 139

    Args:
140
       op_type: The name of the operator to be created.
D
dzhwinter 已提交
141 142 143 144 145 146 147

    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 = \
148
        [output for output in op_proto.outputs if not output.intermediate]
D
dzhwinter 已提交
149
    intermediate_outputs = \
150
        [output for output in op_proto.outputs if output.intermediate]
D
dzhwinter 已提交
151 152 153

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

    if not_intermediate_outputs[0].duplicable:
        raise ValueError(
158
            "Only non duplicable op can be automatically generated.")
D
dzhwinter 已提交
159 160 161 162

    for output in intermediate_outputs:
        if output.duplicable:
            raise ValueError("The op can be automatically generated only when ",
163
                             "all intermediate ops are not duplicable.")
D
dzhwinter 已提交
164 165 166 167

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

Y
Yu Yang 已提交
168
    def infer_and_check_dtype(op_proto, *args, **kwargs):
D
dzhwinter 已提交
169 170 171 172 173 174 175 176 177 178
        """
        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 已提交
179
            if len(val) == 0:
180 181
                if len(args) == 0:
                    continue
Y
Yu Yang 已提交
182 183 184
                val = [args[0]]
                args = args[1:]

D
dzhwinter 已提交
185 186 187 188 189 190 191 192 193 194 195 196
            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))

W
Wu Yi 已提交
197 198 199 200 201 202 203 204 205
        if dtype is None:
            arg_dtype = kwargs.get("dtype")
            if arg_dtype:
                if not isinstance(arg_dtype, core.VarDesc.VarType):
                    dtype = convert_np_dtype_to_dtype_(arg_dtype)
                else:
                    dtype = arg_dtype
            else:
                dtype = core.VarDesc.VarType.FP32
D
dzhwinter 已提交
206 207
        return dtype

Y
Yu Yang 已提交
208
    def func(*args, **kwargs):
D
dzhwinter 已提交
209 210
        helper = LayerHelper(op_type, **kwargs)

Y
Yu Yang 已提交
211
        dtype = infer_and_check_dtype(op_proto, *args, **kwargs)
D
dzhwinter 已提交
212 213 214 215 216 217 218

        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 已提交
219 220 221
            if len(val) == 0 and len(args) != 0:
                val = args[0]
                args = args[1:]
D
dzhwinter 已提交
222 223 224
            inputs[ipt.name] = val

        outputs = dict()
225 226 227 228 229
        out = kwargs.pop(_convert_(o_name), [])
        if out:
            out_var = out[0] if (isinstance(out, list) or
                                 isinstance(out, tuple)) else out
        else:
X
Xin Pan 已提交
230
            out_var = helper.create_variable_for_type_inference(dtype=dtype)
231
        outputs[o_name] = [out_var]
D
dzhwinter 已提交
232
        for name in intermediate_output_names:
X
Xin Pan 已提交
233 234 235
            outputs[name] = [
                helper.create_variable_for_type_inference(dtype=dtype)
            ]
D
dzhwinter 已提交
236 237
        helper.append_op(
            type=op_type, inputs=inputs, outputs=outputs, attrs=kwargs)
238
        return helper.append_activation(out_var)
D
dzhwinter 已提交
239 240 241 242 243 244

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


245
def generate_activation_fn(op_type):
246 247 248 249 250 251 252 253 254 255 256
    """Register the Python layer for an Operator without Attribute.

    Args:
       op_type: The name of the operator to be created.

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

    """
    op_proto = OpProtoHolder.instance().get_op_proto(op_type)

T
tensor-tang 已提交
257
    def func(x, name=None):
258 259
        if in_dygraph_mode():
            op = getattr(core.ops, op_type)
260
            return op(x)
261

262 263 264 265 266 267 268 269 270
        if op_type not in ["abs", "exp", "square"]:
            check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'],
                                     op_type)
        else:
            # abs exp square ops support dtype(int32, int64, float16, float32, float64)
            check_variable_and_dtype(
                x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'],
                op_type)

271 272
        helper = LayerHelper(op_type, **locals())

X
Xin Pan 已提交
273
        output = helper.create_variable_for_type_inference(dtype=x.dtype)
T
tensor-tang 已提交
274
        helper.append_op(type=op_type, inputs={"X": x}, outputs={"Out": output})
275 276 277
        return output

    func.__name__ = op_type
278 279 280
    func.__doc__ = _generate_doc_string_(
        op_proto,
        additional_args_lines=[
281
            "name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`."
282
        ])
283 284 285
    return func


286 287 288 289 290 291 292
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 已提交
293 294


Y
yuyang18 已提交
295
def templatedoc(op_type=None):
Y
yuyang18 已提交
296 297 298 299 300 301 302 303 304 305
    """
    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 已提交
306
        Decorated function.
Y
yuyang18 已提交
307 308
    """

Y
yuyang18 已提交
309 310 311
    def trim_ending_dot(msg):
        return msg.rstrip('.')

Y
yuyang18 已提交
312
    def __impl__(func):
Y
yuyang18 已提交
313 314 315 316 317
        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 已提交
318
        tmpl = string.Template(func.__doc__)
Y
yuyang18 已提交
319 320 321 322

        comment_lines = op_proto.comment.split("\n")
        comment = ""
        for line in comment_lines:
Y
yuyang18 已提交
323 324
            line = line.strip()
            if len(line) != 0:
Y
yuyang18 已提交
325
                comment += escape_math(line)
Y
yuyang18 已提交
326
                comment += " "
Y
yuyang18 已提交
327 328
            elif len(comment) != 0:
                comment += "\n    \n    "
Y
yuyang18 已提交
329

Y
yuyang18 已提交
330
        args = {"comment": trim_ending_dot(comment)}
Y
yuyang18 已提交
331 332
        for each_input in op_proto.inputs:
            input_name = _convert_(each_input.name)
Y
yuyang18 已提交
333 334
            args["{0}_comment".format(input_name)] = trim_ending_dot(
                each_input.comment)
Y
yuyang18 已提交
335 336 337
            args["{0}_type".format(input_name)] = "Variable"
        for each_attr in op_proto.attrs:
            input_name = _convert_(each_attr.name)
Y
yuyang18 已提交
338 339
            args["{0}_comment".format(input_name)] = trim_ending_dot(
                each_attr.comment)
Y
yuyang18 已提交
340 341 342 343
            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 已提交
344 345
            args["{0}_comment".format(output_name)] = trim_ending_dot(
                each_opt.comment)
Y
yuyang18 已提交
346 347 348 349 350
            args["{0}_type".format(output_name)] = "Variable"
        func.__doc__ = tmpl.substitute(args)
        return func

    return __impl__
351 352 353 354 355 356 357 358 359 360 361


def add_sample_code(func, sample_code):
    """
    Append sample code for dynamically generated functions. 

    Args:
       func: The function of the function to be append sample code to.
       sample_code: sample code session in rst format.
    """
    func.__doc__ = func.__doc__ + sample_code