nn.py 12.6 KB
Newer Older
M
minqiyang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

from __future__ import print_function

from six.moves import reduce

from .. import core
from ..layers import utils
from . import layers
from ..framework import Variable, OpProtoHolder
from ..param_attr import ParamAttr
from ..initializer import Normal, Constant

J
JiabinYang 已提交
26
__all__ = ['Conv2D', 'Pool2D', 'FC', 'SimpleRNNCell']
M
minqiyang 已提交
27 28


X
Xin Pan 已提交
29
class Conv2D(layers.Layer):
M
minqiyang 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 padding=0,
                 dilation=1,
                 groups=None,
                 use_cudnn=True,
                 act=None,
                 param_attr=None,
                 bias_attr=None,
                 name=None,
                 dtype=core.VarDesc.VarType.FP32):
        assert param_attr is not False, "param_attr should not be False here."
M
minqiyang 已提交
45 46 47 48 49 50 51 52 53
        super(Conv2D, self).__init__(name=name, dtype=dtype)

        from ..layer_helper import LayerHelper
        self._helper = LayerHelper(
            type(self).__name__,
            param_attr=param_attr,
            bias_attr=bias_attr,
            dtype=dtype,
            name=name)
M
minqiyang 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

        self._groups = groups
        self._stride = utils.convert_to_list(stride, 2, 'stride')
        self._padding = utils.convert_to_list(padding, 2, 'padding')
        self._dilation = utils.convert_to_list(dilation, 2, 'dilation')
        if not isinstance(use_cudnn, bool):
            raise ValueError("use_cudnn should be True or False")
        self._use_cudnn = use_cudnn
        self._num_channels = num_channels
        if (self._num_channels == self._groups and
                num_filters % self._num_channels == 0 and not self._use_cudnn):
            self._l_type = 'depthwise_conv2d'
        else:
            self._l_type = 'conv2d'

        if groups is None:
            num_filter_channels = num_channels
        else:
            if num_channels % groups != 0:
                raise ValueError("num_channels must be divisible by groups.")
            num_filter_channels = num_channels // groups
        filter_size = utils.convert_to_list(filter_size, 2, 'filter_size')
        filter_shape = [num_filters, int(num_filter_channels)] + filter_size

        def _get_default_param_initializer():
            filter_elem_num = filter_size[0] * filter_size[1] * num_channels
            std = (2.0 / filter_elem_num)**0.5
            return Normal(0.0, std, 0)

        self._filter_param = self._helper.create_parameter(
            attr=self._helper.param_attr,
            shape=filter_shape,
            dtype=self._dtype,
            default_initializer=_get_default_param_initializer())

        if self._use_cudnn:
            self._helper.create_variable(
                name="kCUDNNFwdAlgoCache",
                persistable=True,
                type=core.VarDesc.VarType.RAW)
            self._helper.create_variable(
                name="kCUDNNBwdDataAlgoCache",
                persistable=True,
                type=core.VarDesc.VarType.RAW)
            self._helper.create_variable(
                name="kCUDNNBwdFilterAlgoCache",
                persistable=True,
                type=core.VarDesc.VarType.RAW)

M
minqiyang 已提交
103 104
        self._bias_param = self._helper.create_parameter(
            attr=self._helper.bias_attr,
M
minqiyang 已提交
105
            shape=[num_filters],
M
minqiyang 已提交
106 107
            dtype=self._dtype,
            is_bias=True)
M
minqiyang 已提交
108 109

    def forward(self, input):
M
minqiyang 已提交
110 111 112
        pre_bias = self._helper.create_variable_for_type_inference(
            dtype=self._dtype)

M
minqiyang 已提交
113 114 115 116 117 118
        self._helper.append_op(
            type=self._l_type,
            inputs={
                'Input': input,
                'Filter': self._filter_param,
            },
M
minqiyang 已提交
119
            outputs={"Output": pre_bias},
M
minqiyang 已提交
120 121 122 123 124 125 126 127 128
            attrs={
                'strides': self._stride,
                'paddings': self._padding,
                'dilations': self._dilation,
                'groups': self._groups,
                'use_cudnn': self._use_cudnn,
                'use_mkldnn': False,
            })

M
minqiyang 已提交
129 130
        pre_act = self._helper.create_variable_for_type_inference(
            dtype=self._dtype)
M
minqiyang 已提交
131

M
minqiyang 已提交
132 133 134 135 136 137 138 139
        self._helper.append_op(
            type='elementwise_add',
            inputs={'X': [pre_bias],
                    'Y': [self._bias_param]},
            outputs={'Out': [pre_act]},
            attrs={'axis': 1})

        return self._helper.append_activation(pre_act)
M
minqiyang 已提交
140 141


X
Xin Pan 已提交
142
class Pool2D(layers.Layer):
M
minqiyang 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    def __init__(self,
                 pool_size=-1,
                 pool_type="max",
                 pool_stride=1,
                 pool_padding=0,
                 global_pooling=False,
                 use_cudnn=True,
                 ceil_mode=False,
                 exclusive=True,
                 name=None,
                 dtype=core.VarDesc.VarType.FP32):
        if pool_type not in ["max", "avg"]:
            raise ValueError(
                "Unknown pool_type: '%s'. It can only be 'max' or 'avg'.",
                str(pool_type))

        if global_pooling is False and pool_size == -1:
            raise ValueError(
                "When the global_pooling is False, pool_size must be passed "
                "and be a valid value. Received pool_size: " + str(pool_size))

        if not isinstance(use_cudnn, bool):
            raise ValueError("use_cudnn should be True or False")

        super(Pool2D, self).__init__(name=name, dtype=dtype)

M
minqiyang 已提交
169 170 171
        from ..layer_helper import LayerHelper
        self._helper = LayerHelper(type(self).__name__, dtype=dtype, name=name)

M
minqiyang 已提交
172 173 174 175 176 177 178 179 180 181 182 183
        self._pool_type = pool_type
        self._pool_size = utils.convert_to_list(pool_size, 2, 'pool_size')
        self._pool_padding = utils.convert_to_list(pool_padding, 2,
                                                   'pool_padding')
        self._pool_stride = utils.convert_to_list(pool_stride, 2, 'pool_stride')
        self._global_pooling = global_pooling
        self._use_cudnn = use_cudnn
        self._ceil_mode = ceil_mode
        self._exclusive = exclusive
        self._l_type = 'pool2d'

    def forward(self, input):
M
minqiyang 已提交
184 185
        pool_out = self._helper.create_variable_for_type_inference(self._dtype)

M
minqiyang 已提交
186 187 188
        self._helper.append_op(
            type=self._l_type,
            inputs={"X": input},
M
minqiyang 已提交
189
            outputs={"Out": pool_out},
M
minqiyang 已提交
190 191 192 193 194 195 196 197 198 199 200
            attrs={
                "pooling_type": self._pool_type,
                "ksize": self._pool_size,
                "global_pooling": self._global_pooling,
                "strides": self._pool_stride,
                "paddings": self._pool_padding,
                "use_cudnn": self._use_cudnn,
                "ceil_mode": self._ceil_mode,
                "use_mkldnn": False,
                "exclusive": self._exclusive,
            })
M
minqiyang 已提交
201
        return pool_out
M
minqiyang 已提交
202 203


X
Xin Pan 已提交
204
class FC(layers.Layer):
M
minqiyang 已提交
205
    def __init__(self,
M
minqiyang 已提交
206
                 size,
M
minqiyang 已提交
207
                 param_attr=None,
M
minqiyang 已提交
208
                 num_flatten_dims=1,
M
minqiyang 已提交
209
                 dtype=core.VarDesc.VarType.FP32):
M
minqiyang 已提交
210 211
        super(FC, self).__init__()
        self._size = size
M
minqiyang 已提交
212 213
        self._num_flatten_dims = num_flatten_dims
        self._dtype = dtype
M
minqiyang 已提交
214 215
        from ..layer_helper import LayerHelper
        self._helper = LayerHelper('FC', param_attr=param_attr)
M
minqiyang 已提交
216 217 218 219 220

    def _build_once(self, input):
        input_shape = input.shape
        param_shape = [
            reduce(lambda a, b: a * b, input_shape[self._num_flatten_dims:], 1)
M
minqiyang 已提交
221
        ] + [self._size]
M
minqiyang 已提交
222 223 224 225 226 227 228
        self._w = self._helper.create_parameter(
            attr=self._helper.param_attr,
            shape=param_shape,
            dtype=self._dtype,
            is_bias=False)

    def forward(self, input):
M
minqiyang 已提交
229
        tmp = self._helper.create_variable_for_type_inference(self._dtype)
M
minqiyang 已提交
230 231 232 233
        self._helper.append_op(
            type="mul",
            inputs={"X": input,
                    "Y": self._w},
M
minqiyang 已提交
234
            outputs={"Out": tmp},
M
minqiyang 已提交
235 236 237 238 239
            attrs={
                "x_num_col_dims": self._num_flatten_dims,
                "y_num_col_dims": 1
            })

M
minqiyang 已提交
240
        out = self._helper.create_variable_for_type_inference(self._dtype)
M
minqiyang 已提交
241 242
        self._helper.append_op(
            type="sum",
M
minqiyang 已提交
243 244
            inputs={"X": [tmp]},
            outputs={"Out": out},
M
minqiyang 已提交
245
            attrs={"use_mkldnn": False})
M
minqiyang 已提交
246
        return out
J
JiabinYang 已提交
247 248 249


class SimpleRNNCell(layers.Layer):
J
JiabinYang 已提交
250
    def __init__(self, step_input_size, hidden_size, output_size, param_attr):
J
JiabinYang 已提交
251
        super(SimpleRNNCell, self).__init__()
J
JiabinYang 已提交
252
        self.step_input_size = step_input_size
J
JiabinYang 已提交
253 254
        self.hidden_size = hidden_size
        self.output_size = output_size
J
JiabinYang 已提交
255
        self._dype = core.VarDesc.VarType.FP32
J
JiabinYang 已提交
256
        from ..layer_helper import LayerHelper
J
JiabinYang 已提交
257 258
        self._helper = LayerHelper(
            'SimpleRNNCell', act="tanh", param_attr=param_attr)
J
JiabinYang 已提交
259

J
JiabinYang 已提交
260
    def _build_once(self, inputs, pre_hidden):
J
JiabinYang 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        i2h_param_shape = [self.step_input_size, self.hidden_size]
        h2h_param_shape = [self.hidden_size, self.hidden_size]
        h2o_param_shape = [self.output_size, self.hidden_size]
        self._i2h_w = self._helper.create_parameter(
            attr=self._helper.param_attr,
            shape=i2h_param_shape,
            dtype=self._dtype,
            is_bias=False)
        self._h2h_w = self._helper.create_parameter(
            attr=self._helper.param_attr,
            shape=h2h_param_shape,
            dtype=self._dtype,
            is_bias=False)
        self._h2o_w = self._helper.create_parameter(
            attr=self._helper.param_attr,
            shape=h2o_param_shape,
            dtype=self._dtype,
            is_bias=False)

J
JiabinYang 已提交
280
    def forward(self, input, pre_hidden):
J
JiabinYang 已提交
281

J
JiabinYang 已提交
282 283 284 285 286 287
        tmp_i2h = self._helper.create_variable_for_type_inference(self._dtype)
        tmp_h2h = self._helper.create_variable_for_type_inference(self._dtype)
        hidden = self._helper.create_variable_for_type_inference(self._dype)
        out = self._helper.create_variable_for_type_inference(self._dype)
        softmax_out = self._helper.create_variable_for_type_inference(
            self._dtype)
J
JiabinYang 已提交
288

J
JiabinYang 已提交
289 290 291
        self._helper.append_op(
            type="mul",
            inputs={"X": input,
J
JiabinYang 已提交
292 293 294 295
                    "Y": self._i2h_w},
            outputs={"Out": tmp_i2h},
            attrs={"x_num_col_dims": 1,
                   "y_num_col_dims": 1})
J
JiabinYang 已提交
296
        print("mul op 1")
J
JiabinYang 已提交
297 298 299 300 301 302 303
        self._helper.append_op(
            type="mul",
            inputs={"X": pre_hidden,
                    "Y": self._h2h_w},
            outputs={"Out": tmp_h2h},
            attrs={"x_num_col_dims": 1,
                   "y_num_col_dims": 1})
J
JiabinYang 已提交
304
        print("mul op 2")
J
JiabinYang 已提交
305
        self._helper.append_op(
J
JiabinYang 已提交
306 307 308
            type="elementwise_add",
            inputs={'X': tmp_h2h,
                    'Y': tmp_i2h},
J
JiabinYang 已提交
309
            outputs={'Out': hidden},
J
JiabinYang 已提交
310 311 312
            attrs={'axis': -1,
                   'use_mkldnn': False})
        print("elementwise op 1")
J
JiabinYang 已提交
313

J
JiabinYang 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326
        self._helper.append_op(
            type='print',
            inputs={'In': hidden},
            attrs={
                'first_n': -1,
                'summarize': -1,
                'message': None or "",
                'print_tensor_name': True,
                'print_tensor_type': True,
                'print_tensor_shape': True,
                'print_tensor_lod': True,
                'print_phase': 'BOTH'
            })
J
JiabinYang 已提交
327 328
        hidden = self._helper.append_activation(hidden)

J
JiabinYang 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342
        self._helper.append_op(
            type='print',
            inputs={'In': hidden},
            attrs={
                'first_n': -1,
                'summarize': -1,
                'message': None or "",
                'print_tensor_name': True,
                'print_tensor_type': True,
                'print_tensor_shape': True,
                'print_tensor_lod': True,
                'print_phase': 'BOTH'
            })

J
JiabinYang 已提交
343 344 345 346
        self._helper.append_op(
            type="mul",
            inputs={"X": hidden,
                    "Y": self._h2o_w},
J
JiabinYang 已提交
347
            outputs={"Out": out},
J
JiabinYang 已提交
348 349
            attrs={"x_num_col_dims": 1,
                   "y_num_col_dims": 1})
J
JiabinYang 已提交
350
        print("mul op 3")
J
JiabinYang 已提交
351 352 353 354 355 356

        self._helper.append_op(
            type="softmax",
            inputs={"X": out},
            outputs={"Out": softmax_out},
            attrs={"use_cudnn": False})
J
JiabinYang 已提交
357
        print("softmax op 1")
J
JiabinYang 已提交
358

J
JiabinYang 已提交
359
        return softmax_out, hidden