op.py 7.4 KB
Newer Older
Y
Yu Yang 已提交
1
import paddle.v2.framework.core as core
Y
Yu Yang 已提交
2
import paddle.v2.framework.proto.framework_pb2 as framework_pb2
Y
Yu Yang 已提交
3 4 5


def get_all_op_protos():
6
    """
7
    Get all registered op proto from PaddlePaddle C++ end.
8
    :return: A list of registered OpProto.
9
    """
Y
Yu Yang 已提交
10 11 12
    protostrs = core.get_all_op_protos()
    ret_values = []
    for pbstr in protostrs:
Y
Yu Yang 已提交
13
        op_proto = framework_pb2.OpProto.FromString(str(pbstr))
Y
Yu Yang 已提交
14 15
        ret_values.append(op_proto)
    return ret_values
16 17


Y
Yu Yang 已提交
18 19 20 21
def is_str(s):
    return isinstance(s, str) or isinstance(s, unicode)


22 23
class OpDescCreationMethod(object):
    """
24 25
    Convert the user's input(only keyword arguments are supported) to OpDesc
    based on the OpProto.
Y
Yan Chunwei 已提交
26

27 28 29 30 31
    :param op_proto: The OpProto object.
    :type op_proto: op_proto_pb2.OpProto
    """

    def __init__(self, op_proto):
Y
Yu Yang 已提交
32
        if not isinstance(op_proto, framework_pb2.OpProto):
33 34
            raise TypeError(
                "Type of op_proto should be OpProto in PaddlePaddle.")
35 36 37 38
        self.__op_proto__ = op_proto

    def __call__(self, *args, **kwargs):
        """
39
        Convert user's input to OpDesc. Only keyword arguments are supported.
40
        :return: The OpDesc based on user input.
41 42 43
        :rtype: op_desc_pb2.OpDesc
        """
        if len(args) != 0:
44
            raise ValueError("Only keyword arguments are supported.")
Y
Yu Yang 已提交
45 46 47 48 49 50 51
        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:
52 53 54
                raise ValueError(
                    "Input %s expects only one input, but %d are given." %
                    (input_parameter.name, len(input_arguments)))
Y
Yu Yang 已提交
55 56 57 58 59 60 61 62 63 64 65 66

            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(
67
                    "Output %s expects only one output, but %d are given." %
Y
Yu Yang 已提交
68 69 70 71 72
                    (output_parameter.name, len(output_arguments)))

            out = op_desc.outputs.add()
            out.parameter = output_parameter.name
            out.arguments.extend(output_arguments)
73 74 75 76 77 78 79 80 81 82 83 84 85

        # 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
Y
Yu Yang 已提交
86
                if attr.type == framework_pb2.INT:
87
                    new_attr.i = user_defined_attr
Y
Yu Yang 已提交
88
                elif attr.type == framework_pb2.FLOAT:
89
                    new_attr.f = user_defined_attr
Y
Yu Yang 已提交
90
                elif attr.type == framework_pb2.STRING:
91
                    new_attr.s = user_defined_attr
Y
Yu Yang 已提交
92
                elif attr.type == framework_pb2.INTS:
93
                    new_attr.ints.extend(user_defined_attr)
Y
Yu Yang 已提交
94
                elif attr.type == framework_pb2.FLOATS:
95
                    new_attr.floats.extend(user_defined_attr)
Y
Yu Yang 已提交
96
                elif attr.type == framework_pb2.STRINGS:
97
                    new_attr.strings.extend(user_defined_attr)
98 99
                elif attr.type == framework_pb2.INT_PAIRS:
                    for p in user_defined_attr:
W
wanghaoshuang 已提交
100
                        pair = new_attr.int_pairs.add()
101 102
                        pair.first = p[0]
                        pair.second = p[1]
103
                else:
104 105 106
                    raise NotImplementedError(
                        "A not supported attribute type: %s." % (
                            str(attr.type)))
107 108 109 110 111 112

        return op_desc

    @staticmethod
    def any_is_true(generator):
        """
113 114
        Reduce a boolean array to a single boolean parameter. If any element in
        the array is True, this function will return True, otherwise False.
115 116 117 118 119 120 121
        """
        for flag in generator:
            if flag:
                return True
        return False


Y
Yu Yang 已提交
122
class OpInfo(object):
Y
Yu Yang 已提交
123
    def __init__(self, name, method, inputs, outputs, attrs):
Y
Yu Yang 已提交
124 125 126 127 128 129 130
        self.name = name
        self.method = method
        self.inputs = inputs
        self.outputs = outputs
        self.attrs = attrs


131 132
def create_op_creation_method(op_proto):
    """
133
    Generate op creation method for an OpProto.
134 135 136 137 138 139 140
    """
    method = OpDescCreationMethod(op_proto)

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

Y
Yu Yang 已提交
141 142 143
    return OpInfo(
        method=__impl__,
        name=op_proto.type,
144 145
        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 已提交
146
        attrs=[attr.name for attr in op_proto.attrs])
147 148 149 150 151 152 153 154


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 已提交
155
            self.op_methods[method.name] = method
Y
Yu Yang 已提交
156

157
    def __call__(self, *args, **kwargs):
158
        if "type" in kwargs:
159
            if len(args) != 0:
160
                raise ValueError(
161 162 163
                    "Except the argument \"type\","
                    "all of the other arguments should be keyword arguments.")
            t = kwargs.pop("type")
164 165
        else:
            if len(args) != 1:
166
                raise ValueError(
167 168
                    "Except the argument \"type\","
                    "all of the other arguments should be keyword arguments.")
169
            t = args[0]
170

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

Y
Yu Yang 已提交
173 174 175
    def types(self):
        return self.op_methods.keys()

Y
Yu Yang 已提交
176
    def get_op_info(self, t):
177
        if t not in self.op_methods:
178
            raise ValueError("The operator: %s is not registered." % t)
179
        return self.op_methods.get(t)
180

181
    def get_op_input_names(self, type):
182 183 184
        return map(lambda x: x[0], self.get_op_info(type).inputs)

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

187
    def get_op_output_names(self, type):
188 189 190
        return map(lambda x: x[0], self.get_op_info(type).outputs)

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

193
    def get_op_attr_names(self, type):
Y
Yu Yang 已提交
194
        return self.get_op_info(type).attrs
195 196


Y
Yan Chunwei 已提交
197 198
class __RecurrentOp__(object):
    __proto__ = None
199
    type = "recurrent"
Y
Yan Chunwei 已提交
200 201 202 203 204 205 206 207 208

    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):
209 210
        if self.type not in args and "type" not in kwargs:
            kwargs["type"] = self.type
Y
Yan Chunwei 已提交
211 212 213 214 215 216 217
        # create proto
        create_method = OpDescCreationMethod(self.__proto__)
        proto = create_method(*args, **kwargs)
        # create rnnop
        return core.RecurrentOp.create(proto.SerializeToString())


218
Operator = OperatorFactory()  # The default global factory
Y
Yan Chunwei 已提交
219
RecurrentOp = __RecurrentOp__()