layer_helper.py 6.6 KB
Newer Older
Y
Yu Yang 已提交
1 2 3
import copy
import itertools

Y
Yu Yang 已提交
4 5 6 7
import paddle.v2.framework.core as core

from paddle.v2.framework.framework import Variable, g_program, \
    g_init_program
8 9
from paddle.v2.framework.initializer import ConstantInitializer, \
    UniformInitializer
Y
Yu Yang 已提交
10

Y
Yu Yang 已提交
11 12

def unique_name(prefix):
13
    uid = core.unique_integer(prefix)  # unique during whole process.
Y
Yu Yang 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
    return "_".join([prefix, str(uid)])


class LayerHelper(object):
    def __init__(self, layer_type, **kwargs):
        self.kwargs = kwargs
        self.layer_type = layer_type
        name = self.kwargs.get('name', None)
        if name is None:
            self.kwargs['name'] = unique_name(self.layer_type)

    @property
    def name(self):
        return self.kwargs['name']

    @property
    def program(self):
        prog = self.kwargs.get('program', None)
        if prog is None:
            return g_program
        else:
            return prog

Q
QI JUN 已提交
37 38 39 40 41 42 43 44
    @property
    def init_program(self):
        prog = self.kwargs.get('init_program', None)
        if prog is None:
            return g_init_program
        else:
            return prog

Y
Yu Yang 已提交
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
    def append_op(self, *args, **kwargs):
        return self.program.current_block().append_op(*args, **kwargs)

    def multiple_input(self, input_param_name='input'):
        inputs = self.kwargs.get(input_param_name, [])
        type_error = TypeError(
            "Input of {0} layer should be Variable or sequence of Variable".
            format(self.layer_type))
        if isinstance(inputs, Variable):
            inputs = [inputs]
        elif not isinstance(inputs, list) and not isinstance(inputs, tuple):
            raise type_error
        else:
            for each in inputs:
                if not isinstance(each, Variable):
                    raise type_error
        return inputs

    def input(self, input_param_name='input'):
        inputs = self.multiple_input(input_param_name)
        if len(inputs) != 1:
            raise "{0} layer only takes one input".format(self.layer_type)
        return inputs[0]

    @property
    def param_attr(self):
71
        default = {'name': None, 'initializer': UniformInitializer()}
Y
Yu Yang 已提交
72
        actual = self.kwargs.get('param_attr', None)
Y
Yu Yang 已提交
73 74 75 76 77 78
        if actual is None:
            actual = default
        for default_field in default.keys():
            if default_field not in actual:
                actual[default_field] = default[default_field]
        return actual
Y
Yu Yang 已提交
79

Q
QI JUN 已提交
80
    def bias_attr(self):
81
        default = {'name': None, 'initializer': ConstantInitializer()}
82 83
        bias_attr = self.kwargs.get('bias_attr', None)
        if bias_attr is True:
Y
Yu Yang 已提交
84 85 86 87 88 89
            bias_attr = default

        if isinstance(bias_attr, dict):
            for default_field in default.keys():
                if default_field not in bias_attr:
                    bias_attr[default_field] = default[default_field]
Y
Yu Yang 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        return bias_attr

    def multiple_param_attr(self, length):
        param_attr = self.param_attr
        if isinstance(param_attr, dict):
            param_attr = [param_attr]

        if len(param_attr) != 1 and len(param_attr) != length:
            raise ValueError("parameter number mismatch")
        elif len(param_attr) == 1 and length != 1:
            tmp = [None] * length
            for i in xrange(length):
                tmp[i] = copy.deepcopy(param_attr[0])
            param_attr = tmp
        return param_attr

    def iter_inputs_and_params(self, input_param_name='input'):
        inputs = self.multiple_input(input_param_name)
        param_attrs = self.multiple_param_attr(len(inputs))
        for ipt, param_attr in itertools.izip(inputs, param_attrs):
            yield ipt, param_attr

    def input_dtype(self, input_param_name='input'):
        inputs = self.multiple_input(input_param_name)
        dtype = None
        for each in inputs:
            if dtype is None:
                dtype = each.data_type
            elif dtype != each.data_type:
                raise ValueError("Data Type mismatch")
        return dtype

    def create_parameter(self, attr, shape, dtype, suffix='w'):
123 124 125 126
        # Deepcopy the attr so that parameters can be shared in program
        attr_copy = copy.deepcopy(attr)
        if attr_copy['name'] is None:
            attr_copy['name'] = unique_name(".".join([self.name, suffix]))
Q
QI JUN 已提交
127
        self.init_program.global_block().create_parameter(
128
            dtype=dtype, shape=shape, **attr_copy)
Q
QI JUN 已提交
129
        return self.program.global_block().create_parameter(
130
            name=attr_copy['name'], dtype=dtype, shape=shape)
Y
Yu Yang 已提交
131 132 133

    def create_tmp_variable(self, dtype):
        return self.program.current_block().create_var(
Q
QI JUN 已提交
134 135 136
            name=unique_name(".".join([self.name, 'tmp'])),
            dtype=dtype,
            persistable=False)
Y
Yu Yang 已提交
137

Y
Yu Yang 已提交
138 139 140
    def create_variable(self, *args, **kwargs):
        return self.program.current_block().create_var(*args, **kwargs)

Y
Yu Yang 已提交
141
    def create_global_variable(self, *args, **kwargs):
Q
QI JUN 已提交
142 143
        return self.program.global_block().create_var(
            *args, persistable=False, **kwargs)
Y
Yu Yang 已提交
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    def append_bias_op(self, input_var, num_flatten_dims=None):
        """
        Append bias operator and return its output. If the user does not set 
        bias_attr, append_bias_op will return input_var
         
        :param input_var: the input variable. The len(input_var.shape) is larger
        or equal than 2.
        :param num_flatten_dims: The input tensor will be flatten as a matrix 
        when adding bias.
        `matrix.shape = product(input_var.shape[0:num_flatten_dims]), product(
                input_var.shape[num_flatten_dims:])`
        """
        if num_flatten_dims is None:
            num_flatten_dims = self.kwargs.get('num_flatten_dims', None)
            if num_flatten_dims is None:
                num_flatten_dims = 1

        size = list(input_var.shape[num_flatten_dims:])
Q
QI JUN 已提交
163
        bias_attr = self.bias_attr()
Y
Yu Yang 已提交
164 165
        if not bias_attr:
            return input_var
166

Y
Yu Yang 已提交
167
        b = self.create_parameter(
168
            attr=bias_attr, shape=size, dtype=input_var.data_type, suffix='b')
Y
Yu Yang 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        tmp = self.create_tmp_variable(dtype=input_var.data_type)
        self.append_op(
            type='elementwise_add',
            inputs={'X': [input_var],
                    'Y': [b]},
            outputs={'Out': [tmp]})
        return tmp

    def append_activation(self, input_var):
        act = self.kwargs.get('act', None)
        if act is None:
            return input_var
        if isinstance(act, basestring):
            act = {'type': act}
        tmp = self.create_tmp_variable(dtype=input_var.data_type)
        act_type = act.pop('type')
        self.append_op(
            type=act_type,
            inputs={"X": [input_var]},
            outputs={"Y": [tmp]},
            attrs=act)
        return tmp