op.py 9.8 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
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
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

15 16
from __future__ import print_function

M
minqiyang 已提交
17
import numpy as np
18 19
import six

20 21
import paddle.fluid.core as core
import paddle.fluid.proto.framework_pb2 as framework_pb2
Y
Yu Yang 已提交
22 23 24


def get_all_op_protos():
25
    """
26
    Get all registered op proto from PaddlePaddle C++ end.
27
    :return: A list of registered OpProto.
28
    """
Y
Yu Yang 已提交
29 30 31
    protostrs = core.get_all_op_protos()
    ret_values = []
    for pbstr in protostrs:
32
        op_proto = framework_pb2.OpProto.FromString(six.binary_type(pbstr))
Y
Yu Yang 已提交
33 34
        ret_values.append(op_proto)
    return ret_values
35 36


Y
Yu Yang 已提交
37
def is_str(s):
38
    return isinstance(s, six.string_types)
Y
Yu Yang 已提交
39 40


41 42
class OpDescCreationMethod(object):
    """
43 44
    Convert the user's input(only keyword arguments are supported) to OpDesc
    based on the OpProto.
Y
Yan Chunwei 已提交
45

46 47 48 49 50
    :param op_proto: The OpProto object.
    :type op_proto: op_proto_pb2.OpProto
    """

    def __init__(self, op_proto):
Y
Yu Yang 已提交
51
        if not isinstance(op_proto, framework_pb2.OpProto):
52 53
            raise TypeError(
                "Type of op_proto should be OpProto in PaddlePaddle.")
54 55 56 57
        self.__op_proto__ = op_proto

    def __call__(self, *args, **kwargs):
        """
58
        Convert user's input to OpDesc. Only keyword arguments are supported.
59
        :return: The OpDesc based on user input.
60 61 62
        :rtype: op_desc_pb2.OpDesc
        """
        if len(args) != 0:
63
            raise ValueError("Only keyword arguments are supported.")
Y
Yu Yang 已提交
64 65 66 67 68 69 70
        op_desc = framework_pb2.OpDesc()
        for input_parameter in self.__op_proto__.inputs:
            input_arguments = kwargs.get(input_parameter.name, [])
            if is_str(input_arguments):
                input_arguments = [input_arguments]

            if not input_parameter.duplicable and len(input_arguments) > 1:
71 72 73
                raise ValueError(
                    "Input %s expects only one input, but %d are given." %
                    (input_parameter.name, len(input_arguments)))
Y
Yu Yang 已提交
74 75 76 77 78 79 80 81 82 83 84 85

            ipt = op_desc.inputs.add()
            ipt.parameter = input_parameter.name
            ipt.arguments.extend(input_arguments)

        for output_parameter in self.__op_proto__.outputs:
            output_arguments = kwargs.get(output_parameter.name, [])
            if is_str(output_arguments):
                output_arguments = [output_arguments]

            if not output_parameter.duplicable and len(output_arguments) > 1:
                raise ValueError(
86
                    "Output %s expects only one output, but %d are given." %
Y
Yu Yang 已提交
87 88 89 90 91
                    (output_parameter.name, len(output_arguments)))

            out = op_desc.outputs.add()
            out.parameter = output_parameter.name
            out.arguments.extend(output_arguments)
92 93 94 95 96 97 98 99 100 101 102 103 104

        # Types
        op_desc.type = self.__op_proto__.type

        # Attrs
        for attr in self.__op_proto__.attrs:
            if attr.generated:
                continue
            user_defined_attr = kwargs.get(attr.name, None)
            if user_defined_attr is not None:
                new_attr = op_desc.attrs.add()
                new_attr.name = attr.name
                new_attr.type = attr.type
M
minqiyang 已提交
105 106
                if isinstance(user_defined_attr, np.ndarray):
                    user_defined_attr = user_defined_attr.tolist()
Y
Yu Yang 已提交
107
                if attr.type == framework_pb2.INT:
108
                    new_attr.i = user_defined_attr
Y
Yu Yang 已提交
109
                elif attr.type == framework_pb2.FLOAT:
110
                    new_attr.f = user_defined_attr
J
JiabinYang 已提交
111 112
                elif attr.type == framework_pb2.LONG:
                    new_attr.l = user_defined_attr
Y
Yu Yang 已提交
113
                elif attr.type == framework_pb2.STRING:
114
                    new_attr.s = user_defined_attr
115
                elif attr.type == framework_pb2.BOOLEAN:
D
dangqingqing 已提交
116
                    new_attr.b = user_defined_attr
Y
Yu Yang 已提交
117
                elif attr.type == framework_pb2.INTS:
118
                    new_attr.ints.extend(user_defined_attr)
Y
Yu Yang 已提交
119
                elif attr.type == framework_pb2.FLOATS:
120
                    new_attr.floats.extend(user_defined_attr)
Y
Yu Yang 已提交
121
                elif attr.type == framework_pb2.STRINGS:
122
                    new_attr.strings.extend(user_defined_attr)
123
                elif attr.type == framework_pb2.BOOLEANS:
D
dangqingqing 已提交
124
                    new_attr.bools.extend(user_defined_attr)
S
seiriosPlus 已提交
125 126
                elif attr.type == framework_pb2.LONGS:
                    new_attr.longs.extend(user_defined_attr)
127
                else:
128 129 130
                    raise NotImplementedError(
                        "A not supported attribute type: %s." % (
                            str(attr.type)))
131 132 133 134 135 136

        return op_desc

    @staticmethod
    def any_is_true(generator):
        """
137 138
        Reduce a boolean array to a single boolean parameter. If any element in
        the array is True, this function will return True, otherwise False.
139 140 141 142 143 144 145
        """
        for flag in generator:
            if flag:
                return True
        return False


Y
Yu Yang 已提交
146
class OpInfo(object):
Y
Yu Yang 已提交
147
    def __init__(self, name, method, inputs, outputs, attrs):
Y
Yu Yang 已提交
148 149 150 151 152 153 154
        self.name = name
        self.method = method
        self.inputs = inputs
        self.outputs = outputs
        self.attrs = attrs


155 156
def create_op_creation_method(op_proto):
    """
157
    Generate op creation method for an OpProto.
158 159 160 161 162 163 164
    """
    method = OpDescCreationMethod(op_proto)

    def __impl__(*args, **kwargs):
        opdesc = method(*args, **kwargs)
        return core.Operator.create(opdesc.SerializeToString())

Y
Yu Yang 已提交
165 166 167
    return OpInfo(
        method=__impl__,
        name=op_proto.type,
168 169
        inputs=[(var.name, var.duplicable) for var in op_proto.inputs],
        outputs=[(var.name, var.duplicable) for var in op_proto.outputs],
Y
Yu Yang 已提交
170
        attrs=[attr.name for attr in op_proto.attrs])
171 172 173 174 175 176 177 178


class OperatorFactory(object):
    def __init__(self):
        self.op_methods = dict()

        for op_proto in get_all_op_protos():
            method = create_op_creation_method(op_proto)
Y
Yu Yang 已提交
179
            self.op_methods[method.name] = method
Y
Yu Yang 已提交
180

181
    def __call__(self, *args, **kwargs):
182
        if "type" in kwargs:
183
            if len(args) != 0:
184
                raise ValueError(
185 186 187
                    "Except the argument \"type\","
                    "all of the other arguments should be keyword arguments.")
            t = kwargs.pop("type")
188 189
        else:
            if len(args) != 1:
190
                raise ValueError(
191 192
                    "Except the argument \"type\","
                    "all of the other arguments should be keyword arguments.")
193
            t = args[0]
194

Y
Yu Yang 已提交
195
        return self.get_op_info(t).method(**kwargs)
196

Y
Yu Yang 已提交
197
    def types(self):
198
        return list(self.op_methods.keys())
Y
Yu Yang 已提交
199

Y
Yu Yang 已提交
200
    def get_op_info(self, t):
201
        if t not in self.op_methods:
202
            raise ValueError("The operator: %s is not registered." % t)
203
        return self.op_methods.get(t)
204

205
    def get_op_input_names(self, type):
206
        return [x[0] for x in self.get_op_info(type).inputs]
207 208

    def get_op_inputs(self, type):
Y
Yu Yang 已提交
209
        return self.get_op_info(type).inputs
210

211
    def get_op_output_names(self, type):
212
        return [x[0] for x in self.get_op_info(type).outputs]
213 214

    def get_op_outputs(self, type):
Y
Yu Yang 已提交
215
        return self.get_op_info(type).outputs
216

217
    def get_op_attr_names(self, type):
Y
Yu Yang 已提交
218
        return self.get_op_info(type).attrs
219 220


Y
Yan Chunwei 已提交
221 222
class __RecurrentOp__(object):
    __proto__ = None
223
    type = "recurrent"
Y
Yan Chunwei 已提交
224 225 226 227 228 229 230 231 232

    def __init__(self):
        # cache recurrent_op's proto
        if self.__proto__ is None:
            for op_proto in get_all_op_protos():
                if op_proto.type == self.type:
                    self.__proto__ = op_proto

    def __call__(self, *args, **kwargs):
233 234
        if self.type not in args and "type" not in kwargs:
            kwargs["type"] = self.type
Y
Yan Chunwei 已提交
235 236 237 238 239 240 241
        # create proto
        create_method = OpDescCreationMethod(self.__proto__)
        proto = create_method(*args, **kwargs)
        # create rnnop
        return core.RecurrentOp.create(proto.SerializeToString())


242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
class __DynamicRecurrentOp__(object):
    __proto__ = None
    type = "dynamic_recurrent"

    def __init__(self):
        # cache recurrent_op's proto
        if self.__proto__ is None:
            for op_proto in get_all_op_protos():
                if op_proto.type == self.type:
                    self.__proto__ = op_proto

    def __call__(self, *args, **kwargs):
        if self.type not in args and "type" not in kwargs:
            kwargs["type"] = self.type
        # create proto
        create_method = OpDescCreationMethod(self.__proto__)
        proto = create_method(*args, **kwargs)
        # create rnnop
        return core.DynamicRecurrentOp.create(proto.SerializeToString())


Z
cond op  
zchen0211 已提交
263 264
class __CondOp__(object):
    __proto__ = None
Z
zchen0211 已提交
265
    type = "cond"
Z
cond op  
zchen0211 已提交
266 267 268 269 270 271 272 273 274

    def __init__(self):
        # cache recurrent_op's proto
        if self.__proto__ is None:
            for op_proto in get_all_op_protos():
                if op_proto.type == self.type:
                    self.__proto__ = op_proto

    def __call__(self, *args, **kwargs):
Z
zchen0211 已提交
275 276
        if self.type not in args and "type" not in kwargs:
            kwargs["type"] = self.type
Z
cond op  
zchen0211 已提交
277 278 279 280 281 282 283
        # create proto
        create_method = OpDescCreationMethod(self.__proto__)
        proto = create_method(*args, **kwargs)
        # create condop
        return core.CondOp.create(proto.SerializeToString())


284
Operator = OperatorFactory()  # The default global factory
Y
Yan Chunwei 已提交
285
RecurrentOp = __RecurrentOp__()
286
DynamicRecurrentOp = __DynamicRecurrentOp__()
Z
cond op  
zchen0211 已提交
287
CondOp = __CondOp__()