op.py 6.0 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 8 9
    """
    Get all registered op proto from Paddle C++
    :return: list of OpProto
    """
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 24 25 26 27 28 29 30 31
class OpDescCreationMethod(object):
    """
    A Functor object to convert user input(use key word args) to OpDesc based on
    OpProto.
    
    :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 35 36 37 38 39 40 41 42 43
            raise TypeError("Argument should be OpProto")
        self.__op_proto__ = op_proto

    def __call__(self, *args, **kwargs):
        """
        Convert user input to OpDesc. Only key-word args are supported. 
        :return: OpDesc based on user input
        :rtype: op_desc_pb2.OpDesc
        """
        if len(args) != 0:
            raise ValueError("Only keyword arguments is supported by Paddle")
Y
Yu Yang 已提交
44 45 46 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
        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:
                raise ValueError("Input %s only accept one output, but give %d"
                                 % (input_parameter.name, len(input_arguments)))

            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(
                    "Output %s only accept one output, but give %d" %
                    (output_parameter.name, len(output_arguments)))

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

        # 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 已提交
85
                if attr.type == framework_pb2.INT:
86
                    new_attr.i = user_defined_attr
Y
Yu Yang 已提交
87
                elif attr.type == framework_pb2.FLOAT:
88
                    new_attr.f = user_defined_attr
Y
Yu Yang 已提交
89
                elif attr.type == framework_pb2.STRING:
90
                    new_attr.s = user_defined_attr
Y
Yu Yang 已提交
91
                elif attr.type == framework_pb2.INTS:
92
                    new_attr.ints.extend(user_defined_attr)
Y
Yu Yang 已提交
93
                elif attr.type == framework_pb2.FLOATS:
94
                    new_attr.floats.extend(user_defined_attr)
Y
Yu Yang 已提交
95
                elif attr.type == framework_pb2.STRINGS:
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
                    new_attr.strings.extend(user_defined_attr)
                else:
                    raise NotImplementedError("Not support attribute type " +
                                              attr.type)

        return op_desc

    @staticmethod
    def any_is_true(generator):
        """
        Reduce a bool array to one. If any of them is True, then return True.
        """
        for flag in generator:
            if flag:
                return True
        return False


Y
Yu Yang 已提交
114
class OpInfo(object):
Y
Yu Yang 已提交
115
    def __init__(self, name, method, inputs, outputs, attrs):
Y
Yu Yang 已提交
116 117 118 119 120 121 122
        self.name = name
        self.method = method
        self.inputs = inputs
        self.outputs = outputs
        self.attrs = attrs


123 124 125 126 127 128 129 130 131 132
def create_op_creation_method(op_proto):
    """
    Generate op creation method for an OpProto
    """
    method = OpDescCreationMethod(op_proto)

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

Y
Yu Yang 已提交
133 134 135 136 137
    return OpInfo(
        method=__impl__,
        name=op_proto.type,
        inputs=[var.name for var in op_proto.inputs],
        outputs=[var.name for var in op_proto.outputs],
Y
Yu Yang 已提交
138
        attrs=[attr.name for attr in op_proto.attrs])
139 140 141 142 143 144 145


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

148 149 150 151 152 153 154 155 156 157 158
    def __call__(self, *args, **kwargs):
        if 'type' in kwargs:
            if len(args) != 0:
                raise ValueError("All Paddle argument should be key-word "
                                 "argument except type")
            t = kwargs.pop('type')
        else:
            if len(args) != 1:
                raise ValueError("All Paddle argument should be key-word "
                                 "argument except type")
            t = args[0]
159

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

Y
Yu Yang 已提交
162 163 164
    def types(self):
        return self.op_methods.keys()

Y
Yu Yang 已提交
165
    def get_op_info(self, t):
166 167 168
        if t not in self.op_methods:
            raise ValueError("operator %s is not registered", t)
        return self.op_methods.get(t)
169

170
    def get_op_input_names(self, type):
Y
Yu Yang 已提交
171
        return self.get_op_info(type).inputs
172

173
    def get_op_output_names(self, type):
Y
Yu Yang 已提交
174
        return self.get_op_info(type).outputs
175

176
    def get_op_attr_names(self, type):
Y
Yu Yang 已提交
177
        return self.get_op_info(type).attrs
178 179


180
Operator = OperatorFactory()  # Default global factory