nn.py 14.2 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 26 27 28 29
# 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

__all__ = [
    'Conv2D',
    'Pool2D',
    'FC',
M
minqiyang 已提交
30
    'BatchNorm',
M
minqiyang 已提交
31 32 33
]


X
Xin Pan 已提交
34
class Conv2D(layers.Layer):
M
minqiyang 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    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 已提交
50 51
        super(Conv2D, self).__init__(name=name, dtype=dtype)

X
Xin Pan 已提交
52
        # TODO(minqiyang): Move this to the top.
M
minqiyang 已提交
53 54 55 56 57 58
        from ..layer_helper import LayerHelper
        self._helper = LayerHelper(
            type(self).__name__,
            param_attr=param_attr,
            bias_attr=bias_attr,
            dtype=dtype,
M
minqiyang 已提交
59 60
            name=name,
            act=act)
M
minqiyang 已提交
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 103 104 105 106 107 108 109

        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 已提交
110 111
        self._bias_param = self._helper.create_parameter(
            attr=self._helper.bias_attr,
M
minqiyang 已提交
112
            shape=[num_filters],
M
minqiyang 已提交
113 114
            dtype=self._dtype,
            is_bias=True)
M
minqiyang 已提交
115 116

    def forward(self, input):
M
minqiyang 已提交
117 118 119
        pre_bias = self._helper.create_variable_for_type_inference(
            dtype=self._dtype)

M
minqiyang 已提交
120 121 122 123 124 125
        self._helper.append_op(
            type=self._l_type,
            inputs={
                'Input': input,
                'Filter': self._filter_param,
            },
M
minqiyang 已提交
126
            outputs={"Output": pre_bias},
M
minqiyang 已提交
127 128 129 130 131 132 133 134 135
            attrs={
                'strides': self._stride,
                'paddings': self._padding,
                'dilations': self._dilation,
                'groups': self._groups,
                'use_cudnn': self._use_cudnn,
                'use_mkldnn': False,
            })

M
minqiyang 已提交
136 137
        pre_act = self._helper.create_variable_for_type_inference(
            dtype=self._dtype)
M
minqiyang 已提交
138

M
minqiyang 已提交
139 140 141 142 143 144 145
        self._helper.append_op(
            type='elementwise_add',
            inputs={'X': [pre_bias],
                    'Y': [self._bias_param]},
            outputs={'Out': [pre_act]},
            attrs={'axis': 1})

M
minqiyang 已提交
146
        # Currently, we don't support inplace in imperative mode
M
minqiyang 已提交
147
        return self._helper.append_activation(pre_act)
M
minqiyang 已提交
148 149


X
Xin Pan 已提交
150
class Pool2D(layers.Layer):
M
minqiyang 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    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 已提交
177 178 179
        from ..layer_helper import LayerHelper
        self._helper = LayerHelper(type(self).__name__, dtype=dtype, name=name)

M
minqiyang 已提交
180 181 182 183 184 185 186 187 188 189 190 191
        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 已提交
192 193
        pool_out = self._helper.create_variable_for_type_inference(self._dtype)

M
minqiyang 已提交
194 195 196
        self._helper.append_op(
            type=self._l_type,
            inputs={"X": input},
M
minqiyang 已提交
197
            outputs={"Out": pool_out},
M
minqiyang 已提交
198 199 200 201 202 203 204 205 206 207 208
            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 已提交
209
        return pool_out
M
minqiyang 已提交
210 211


X
Xin Pan 已提交
212
class FC(layers.Layer):
M
minqiyang 已提交
213
    def __init__(self,
M
minqiyang 已提交
214
                 size,
M
minqiyang 已提交
215
                 param_attr=None,
M
minqiyang 已提交
216
                 bias_attr=None,
M
minqiyang 已提交
217
                 num_flatten_dims=1,
X
Xin Pan 已提交
218
                 dtype=core.VarDesc.VarType.FP32,
M
minqiyang 已提交
219 220
                 act=None,
                 name=None):
M
minqiyang 已提交
221
        super(FC, self).__init__()
M
minqiyang 已提交
222

M
minqiyang 已提交
223
        self._size = size
M
minqiyang 已提交
224 225
        self._num_flatten_dims = num_flatten_dims
        self._dtype = dtype
M
minqiyang 已提交
226
        from ..layer_helper import LayerHelper
M
minqiyang 已提交
227 228 229 230 231 232
        self._helper = LayerHelper(
            'FC',
            param_attr=param_attr,
            bias_attr=bias_attr,
            act=act,
            name=name)
M
minqiyang 已提交
233

X
Xin Pan 已提交
234
    def parameters(self):
X
Xin Pan 已提交
235
        return [self._w, self._b]
M
minqiyang 已提交
236 237 238 239 240

    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 已提交
241
        ] + [self._size]
M
minqiyang 已提交
242 243 244 245 246
        self._w = self._helper.create_parameter(
            attr=self._helper.param_attr,
            shape=param_shape,
            dtype=self._dtype,
            is_bias=False)
247 248 249 250 251 252 253 254 255 256

        if self._helper.bias_attr:
            size = list([self._size])
            self._b = self._helper.create_parameter(
                attr=self._helper.bias_attr,
                shape=size,
                dtype=self._dtype,
                is_bias=True)
        else:
            self._b = None
M
minqiyang 已提交
257 258

    def forward(self, input):
M
minqiyang 已提交
259
        tmp = self._helper.create_variable_for_type_inference(self._dtype)
M
minqiyang 已提交
260 261 262 263
        self._helper.append_op(
            type="mul",
            inputs={"X": input,
                    "Y": self._w},
M
minqiyang 已提交
264
            outputs={"Out": tmp},
M
minqiyang 已提交
265 266 267 268 269
            attrs={
                "x_num_col_dims": self._num_flatten_dims,
                "y_num_col_dims": 1
            })

M
minqiyang 已提交
270
        pre_bias = self._helper.create_variable_for_type_inference(self._dtype)
M
minqiyang 已提交
271 272
        self._helper.append_op(
            type="sum",
M
minqiyang 已提交
273
            inputs={"X": [tmp]},
M
minqiyang 已提交
274
            outputs={"Out": pre_bias},
M
minqiyang 已提交
275
            attrs={"use_mkldnn": False})
M
minqiyang 已提交
276

277 278 279 280 281 282 283 284 285 286 287
        if self._b:
            pre_activation = self._helper.create_variable_for_type_inference(
                dtype=self._dtype)
            self._helper.append_op(
                type='elementwise_add',
                inputs={'X': [pre_bias],
                        'Y': [self._b]},
                outputs={'Out': [pre_activation]},
                attrs={'axis': self._num_flatten_dims})
        else:
            pre_activation = pre_bias
M
minqiyang 已提交
288
        # Currently, we don't support inplace in imperative mode
M
minqiyang 已提交
289
        return self._helper.append_activation(pre_activation)
M
minqiyang 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315


class BatchNorm(layers.Layer):
    def __init__(self,
                 num_channels,
                 act=None,
                 is_test=False,
                 momentum=0.9,
                 epsilon=1e-05,
                 param_attr=None,
                 bias_attr=None,
                 dtype=core.VarDesc.VarType.FP32,
                 data_layout='NCHW',
                 in_place=False,
                 name=None,
                 moving_mean_name=None,
                 moving_variance_name=None,
                 do_model_average_for_mean_and_var=False,
                 fuse_with_relu=False,
                 use_global_stats=False):
        super(BatchNorm, self).__init__()

        assert bias_attr is not False, "bias_attr should not be False in batch_norm."

        from ..layer_helper import LayerHelper
        self._helper = LayerHelper(
M
minqiyang 已提交
316 317 318 319 320
            'batch_norm',
            param_attr=param_attr,
            bias_attr=bias_attr,
            name=name,
            act=act)
M
minqiyang 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334

        if dtype == core.VarDesc.VarType.FP16:
            self._dtype = core.VarDesc.VarType.FP32
        else:
            self._dtype = dtype

        param_shape = [num_channels]

        # create parameter
        self._scale = self._helper.create_parameter(
            attr=self._helper.param_attr,
            shape=param_shape,
            dtype=self._dtype,
            default_initializer=Constant(1.0))
M
minqiyang 已提交
335 336
        if use_global_stats and self._helper.param_attr.learning_rate == 0.:
            self._scale.stop_gradient = True
M
minqiyang 已提交
337 338 339 340 341 342

        self._bias = self._helper.create_parameter(
            attr=self._helper.bias_attr,
            shape=param_shape,
            dtype=self._dtype,
            is_bias=True)
M
minqiyang 已提交
343 344
        if use_global_stats and self._helper.bias_attr.learning_rate == 0.:
            self._bias.stop_gradient = True
M
minqiyang 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

        self._mean = self._helper.create_parameter(
            attr=ParamAttr(
                name=moving_mean_name,
                initializer=Constant(0.0),
                trainable=False,
                do_model_average=do_model_average_for_mean_and_var),
            shape=param_shape,
            dtype=self._dtype)
        self._mean.stop_gradient = True

        self._variance = self._helper.create_parameter(
            attr=ParamAttr(
                name=moving_variance_name,
                initializer=Constant(1.0),
                trainable=False,
                do_model_average=do_model_average_for_mean_and_var),
            shape=param_shape,
            dtype=self._dtype)
        self._variance.stop_gradient = True

        self._in_place = in_place
        self._momentum = momentum
        self._epsilon = epsilon
        self._is_test = is_test
        self._fuse_with_relu = fuse_with_relu
        self._use_global_stats = use_global_stats

    def _build_once(self, input):
        pass

    def forward(self, input):
        # create output
        # mean and mean_out share the same memory
        mean_out = self._mean
        # variance and variance out share the same memory
        variance_out = self._variance

        saved_mean = self._helper.create_variable_for_type_inference(
M
minqiyang 已提交
384
            dtype=self._dtype, stop_gradient=True)
M
minqiyang 已提交
385
        saved_variance = self._helper.create_variable_for_type_inference(
M
minqiyang 已提交
386
            dtype=self._dtype, stop_gradient=True)
M
minqiyang 已提交
387
        batch_norm_out = input if self._in_place else self._helper.create_variable_for_type_inference(
M
minqiyang 已提交
388
            self._dtype)
M
minqiyang 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

        self._helper.append_op(
            type="batch_norm",
            inputs={
                "X": input,
                "Scale": self._scale,
                "Bias": self._bias,
                "Mean": self._mean,
                "Variance": self._variance
            },
            outputs={
                "Y": batch_norm_out,
                "MeanOut": mean_out,
                "VarianceOut": variance_out,
                "SavedMean": saved_mean,
                "SavedVariance": saved_variance
            },
            attrs={
                "momentum": self._momentum,
                "epsilon": self._epsilon,
                "is_test": self._is_test,
                "use_mkldnn": False,
                "fuse_with_relu": self._fuse_with_relu,
                "use_global_stats": self._use_global_stats
            })

M
minqiyang 已提交
415
        # Currently, we don't support inplace in imperative mode
M
minqiyang 已提交
416
        return self._helper.append_activation(batch_norm_out)