norm.py 53.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 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.

15 16 17 18 19 20 21 22 23 24 25 26 27
#
# 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.

28
# TODO: define normalization api
29

30
import six
31

Z
zhiboniu 已提交
32 33
from ...fluid.dygraph import BatchNorm  # noqa: F401
from ...fluid.dygraph import SpectralNorm  # noqa: F401
C
ceci3 已提交
34

35
from ...framework import get_default_dtype, set_default_dtype, _non_static_mode
C
ceci3 已提交
36

Z
zhiboniu 已提交
37 38
from ..initializer import Constant
from ...framework import ParamAttr
C
ceci3 已提交
39
from ...fluid.data_feeder import check_variable_and_dtype, check_type
Z
zhiboniu 已提交
40
from ...fluid import dygraph_utils
41 42 43 44 45 46

from ..functional import batch_norm, layer_norm, instance_norm

import numpy as np
import numbers
import warnings
Z
zhiboniu 已提交
47
from ...framework import no_grad
48
from .. import functional as F
49
from paddle import _C_ops, _legacy_C_ops
Z
zhiboniu 已提交
50
from .. import Layer
Z
zhiboniu 已提交
51
from paddle import in_dynamic_mode
52
from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph
53

54 55
__all__ = []

C
ceci3 已提交
56

Z
zhiboniu 已提交
57
class _InstanceNormBase(Layer):
58
    """
L
Ligoml 已提交
59
    This class is based class for InstanceNorm1D, 2d, 3d.
60

C
cnn 已提交
61
    See InstaceNorm1D, InstanceNorm2D or InstanceNorm3D for more details.
62 63
    """

L
Ligoml 已提交
64 65 66 67 68 69 70 71 72 73
    def __init__(
        self,
        num_features,
        epsilon=1e-5,
        momentum=0.9,
        weight_attr=None,
        bias_attr=None,
        data_format="NCHW",
        name=None,
    ):
74 75 76
        super(_InstanceNormBase, self).__init__()

        if weight_attr == False or bias_attr == False:
L
Ligoml 已提交
77 78 79
            assert (
                weight_attr == bias_attr
            ), "weight_attr and bias_attr must be set to Fasle at the same time in InstanceNorm"
80 81 82
        self._epsilon = epsilon
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
83
        self._num_features = num_features
84 85 86 87 88 89

        if weight_attr != False and bias_attr != False:
            self.scale = self.create_parameter(
                attr=self._weight_attr,
                shape=[num_features],
                default_initializer=Constant(1.0),
L
Ligoml 已提交
90 91 92 93 94 95 96 97
                is_bias=False,
            )
            self.bias = self.create_parameter(
                attr=self._bias_attr,
                shape=[num_features],
                default_initializer=Constant(0.0),
                is_bias=True,
            )
98 99 100 101 102 103 104 105 106 107
        else:
            self.scale = None
            self.bias = None

    def _check_input_dim(self, input):
        raise NotImplementedError("InstanceNorm Base error")

    def forward(self, input):
        self._check_input_dim(input)

L
Ligoml 已提交
108 109 110
        return instance_norm(
            input, weight=self.scale, bias=self.bias, eps=self._epsilon
        )
111

112
    def extra_repr(self):
L
Ligoml 已提交
113 114 115
        return 'num_features={}, epsilon={}'.format(
            self._num_features, self._epsilon
        )
116

117

C
cnn 已提交
118
class InstanceNorm1D(_InstanceNormBase):
119
    r"""
L
Ligoml 已提交
120
    Create a callable object of `InstanceNorm1D`. Applies Instance Normalization over a 3D input (a mini-batch of 1D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization .
121 122 123 124 125 126 127

    DataLayout: NCL `[batch, in_channels, length]`

    :math:`input` is the input features over a mini-batch.

    ..  math::
        
128 129 130 131 132 133 134
        \mu_{\beta} &\gets \frac{1}{HW} \sum_{i=1}^{HW} x_i \qquad &//\
        \ mean\ of\ one\  feature\ map\ in\ mini-batch \\
        \sigma_{\beta}^{2} &\gets \frac{1}{HW} \sum_{i=1}^{HW}(x_i - \
        \mu_{\beta})^2 \qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\
        \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
135

L
Ligoml 已提交
136
Where `H` means height of feature map, `W` means width of feature map.
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): A value added to the denominator for
            numerical stability. Default is 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
             of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm
	     will create ParamAttr as weight_attr, the name of scale can be set in ParamAttr.
	     If the Initializer of the weight_attr is not set, the parameter is initialized 
	     one. If it is set to False, will not create weight_attr. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm.
             If it is set to None or one attribute of ParamAttr, instance_norm
	     will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. 
	     If the Initializer of the bias_attr is not set, the bias is initialized zero. 
             If it is set to False, will not create bias_attr. Default: None.
153
        data_format(str, optional): Specify the input data format, may be "NC", "NCL". Default "NCL".
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
        name(str, optional): Name for the InstanceNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..


    Shape:
        - x: 2-D or 3-D tensor with shape: (batch, num_features) or (batch, num_features, length).
        - output: 3-D tensor with same shape as input x.

    Returns:
        None.


    Examples:

        .. code-block:: python

          import paddle

L
Ligoml 已提交
171
          x = paddle.rand((2, 2, 3))
C
cnn 已提交
172
          instance_norm = paddle.nn.InstanceNorm1D(2)
173 174
          instance_norm_out = instance_norm(x)

Z
zhang wenhui 已提交
175
          print(instance_norm_out)
176 177 178 179 180

    """

    def _check_input_dim(self, input):
        if len(input.shape) != 2 and len(input.shape) != 3:
L
Ligoml 已提交
181 182 183 184 185
            raise ValueError(
                'expected 2D or 3D input (got {}D input)'.format(
                    len(input.shape)
                )
            )
186 187


C
cnn 已提交
188
class InstanceNorm2D(_InstanceNormBase):
189
    r"""
L
Ligoml 已提交
190
    Create a callable object of `InstanceNorm2D`. Applies Instance Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization .
191 192 193 194 195 196 197 198

    DataLayout: NCHW `[batch, in_channels, in_height, in_width]`


    :math:`input` is the input features over a mini-batch.

    ..  math::
        
199 200 201 202 203 204 205
        \mu_{\beta} &\gets \frac{1}{HW} \sum_{i=1}^{HW} x_i \qquad &//\
        \ mean\ of\ one\  feature\ map\ in\ mini-batch \\
        \sigma_{\beta}^{2} &\gets \frac{1}{HW} \sum_{i=1}^{HW}(x_i - \
        \mu_{\beta})^2 \qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\
        \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
206

L
Ligoml 已提交
207
Where `H` means height of feature map, `W` means width of feature map.
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240

    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): A value added to the denominator for
            numerical stability. Default is 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
             of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm
	     will create ParamAttr as weight_attr, the name of scale can be set in ParamAttr.
	     If the Initializer of the weight_attr is not set, the parameter is initialized 
	     one. If it is set to False, will not create weight_attr. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm.
             If it is set to None or one attribute of ParamAttr, instance_norm
	     will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. 
	     If the Initializer of the bias_attr is not set, the bias is initialized zero. 
             If it is set to False, will not create bias_attr. Default: None.
        data_format(str, optional): Specify the input data format, could be "NCHW". Default: NCHW.
        name(str, optional): Name for the InstanceNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
        - x: 4-D tensor with shape: (batch, num_features, height, weight).
        - output: 4-D tensor with same shape as input x.

    Returns:
        None.


    Examples:

        .. code-block:: python

          import paddle

L
Ligoml 已提交
241
          x = paddle.rand((2, 2, 2, 3))
C
cnn 已提交
242
          instance_norm = paddle.nn.InstanceNorm2D(2)
243 244
          instance_norm_out = instance_norm(x)

Z
zhang wenhui 已提交
245
          print(instance_norm_out)
246 247 248 249
    """

    def _check_input_dim(self, input):
        if len(input.shape) != 4:
L
Ligoml 已提交
250 251 252
            raise ValueError(
                'expected 4D input (got {}D input)'.format(len(input.shape))
            )
253 254


C
cnn 已提交
255
class InstanceNorm3D(_InstanceNormBase):
256
    r"""
L
Ligoml 已提交
257
    Create a callable object of `InstanceNorm3D`. Applies Instance Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization .
258 259 260 261 262 263 264 265

    DataLayout: NCHW `[batch, in_channels, D, in_height, in_width]`


    :math:`input` is the input features over a mini-batch.

    ..  math::
        
266 267 268 269 270 271 272
        \mu_{\beta} &\gets \frac{1}{HW} \sum_{i=1}^{HW} x_i \qquad &//\
        \ mean\ of\ one\  feature\ map\ in\ mini-batch \\
        \sigma_{\beta}^{2} &\gets \frac{1}{HW} \sum_{i=1}^{HW}(x_i - \
        \mu_{\beta})^2 \qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\
        \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
273

L
Ligoml 已提交
274
Where `H` means height of feature map, `W` means width of feature map.
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): A value added to the denominator for
            numerical stability. Default is 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
             of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm
	     will create ParamAttr as weight_attr, the name of scale can be set in ParamAttr.
	     If the Initializer of the weight_attr is not set, the parameter is initialized 
	     one. If it is set to False, will not create weight_attr. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm.
             If it is set to None or one attribute of ParamAttr, instance_norm
	     will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. 
	     If the Initializer of the bias_attr is not set, the bias is initialized zero. 
             If it is set to False, will not create bias_attr. Default: None.
        data_format(str, optional): Specify the input data format, could be "NCDHW". Default: NCDHW.
        name(str, optional): Name for the InstanceNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
        - x: 5-D tensor with shape: (batch, num_features, dims, height, weight).
        - output: 5-D tensor with same shape as input x.

    Returns:
        None.


    Examples:

        .. code-block:: python

          import paddle

L
Ligoml 已提交
308
          x = paddle.rand((2, 2, 2, 2, 3))
C
cnn 已提交
309
          instance_norm = paddle.nn.InstanceNorm3D(2)
310 311
          instance_norm_out = instance_norm(x)

Z
zhang wenhui 已提交
312
          print(instance_norm_out.numpy)
313 314 315 316
    """

    def _check_input_dim(self, input):
        if len(input.shape) != 5:
L
Ligoml 已提交
317 318 319
            raise ValueError(
                'expected 5D input (got {}D input)'.format(len(input.shape))
            )
320 321


Z
zhiboniu 已提交
322
class GroupNorm(Layer):
323
    """
324

325 326 327 328 329 330 331
    This interface is used to construct a callable object of the ``GroupNorm`` class.
    For more details, refer to code examples.
    It implements the function of the Group Normalization Layer.
    Refer to `Group Normalization <https://arxiv.org/abs/1803.08494>`_ .

    Parameters:
        num_groups(int): The number of groups that divided from channels.
332
        num_channels(int): The number of channels of input.
333 334 335 336 337 338 339 340 341 342 343 344
        epsilon(float, optional): The small value added to the variance to prevent
                                  division by zero. Default: 1e-05.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
                                         scale :math:`g`. If it is set to False, no scale will be added to the output units.
                                         If it is set to None, the bias is initialized one. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
                                        bias :math:`b`. If it is set to False, no bias will be added to the output units.
                                        If it is set to None, the bias is initialized zero. Default: None.
        data_format(str, optional): Specify the input data format. Only NCHW is supported. Default: NCHW.
        name(str, optional): Name for the GroupNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
345
        - x: Tensor with shape: attr:`(batch, num_features, *)`.
346
        - output: The same shape as input x.
347 348 349 350 351 352

    Returns:
        None

    Examples:
        .. code-block:: python
Z
zhang wenhui 已提交
353

354
            import paddle
355

356 357 358
            x = paddle.arange(48, dtype="float32").reshape((2, 6, 2, 2))
            group_norm = paddle.nn.GroupNorm(num_channels=6, num_groups=6)
            group_norm_out = group_norm(x)
359

360
            print(group_norm_out)
361 362
    """

L
Ligoml 已提交
363 364 365 366 367 368 369 370 371 372
    def __init__(
        self,
        num_groups,
        num_channels,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        data_format='NCHW',
        name=None,
    ):
373 374 375 376 377 378
        super(GroupNorm, self).__init__()
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
        self._epsilon = epsilon
        self._num_channels = num_channels
        self._num_groups = num_groups
379
        if data_format != 'NCHW':
380
            raise ValueError("unsupported data layout:" + data_format)
381 382 383

        param_shape = [self._num_channels]

384 385
        if weight_attr == False:
            self.weight = self.create_parameter(
L
Ligoml 已提交
386 387
                attr=None, shape=param_shape, default_initializer=Constant(1.0)
            )
388 389 390 391 392
            self.weight.stop_gradient = True
        else:
            self.weight = self.create_parameter(
                attr=self._weight_attr,
                shape=param_shape,
L
Ligoml 已提交
393 394 395 396 397 398
                default_initializer=Constant(1.0),
            )
            self.weight.stop_gradient = (
                self._weight_attr != None
                and self._weight_attr.learning_rate == 0.0
            )
399

400
        if bias_attr == False:
L
Ligoml 已提交
401 402 403 404 405 406
            self.bias = self.create_parameter(
                attr=None,
                shape=param_shape,
                default_initializer=Constant(0.0),
                is_bias=True,
            )
407 408
            self.bias.stop_gradient = True
        else:
L
Ligoml 已提交
409 410 411 412 413 414
            self.bias = self.create_parameter(
                attr=self._bias_attr, shape=param_shape, is_bias=True
            )
            self.bias.stop_gradient = (
                self._bias_attr != None and self._bias_attr.learning_rate == 0.0
            )
415 416

    def forward(self, input):
417
        mean_out = self._helper.create_variable_for_type_inference(
L
Ligoml 已提交
418 419
            dtype=input.dtype, stop_gradient=True
        )
420
        variance_out = self._helper.create_variable_for_type_inference(
L
Ligoml 已提交
421 422
            dtype=input.dtype, stop_gradient=True
        )
423

424
        if in_dygraph_mode():
L
Ligoml 已提交
425 426 427 428 429 430 431 432
            pre_act = _C_ops.group_norm(
                input,
                self.weight,
                self.bias,
                self._epsilon,
                self._num_groups,
                "NCHW",
            )
433

L
Ligoml 已提交
434 435 436
            return dygraph_utils._append_activation_in_dygraph(
                pre_act, act=None
            )
437 438

        elif _in_legacy_dygraph():
439
            pre_act, _, _ = _legacy_C_ops.group_norm(
440 441 442 443 444 445 446 447
                input,
                self.weight,
                self.bias,
                mean_out,
                variance_out,
                'epsilon',
                self._epsilon,
                'groups',
448 449
                self._num_groups,
            )
L
Ligoml 已提交
450 451 452
            return dygraph_utils._append_activation_in_dygraph(
                pre_act, act=None
            )
453

454 455 456 457 458 459 460 461
        inputs = {'X': input}
        if self.bias is not None:
            inputs['Bias'] = self.bias
        if self.weight is not None:
            inputs['Scale'] = self.weight

        # create output
        group_norm_out = self._helper.create_variable_for_type_inference(
L
Ligoml 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474
            dtype=input.dtype
        )

        self._helper.append_op(
            type="group_norm",
            inputs=inputs,
            outputs={
                "Y": group_norm_out,
                "Mean": mean_out,
                "Variance": variance_out,
            },
            attrs={"epsilon": self._epsilon, "groups": self._num_groups},
        )
475 476 477

        return self._helper.append_activation(group_norm_out, None)

478 479
    def extra_repr(self):
        return 'num_groups={}, num_channels={}, epsilon={}'.format(
L
Ligoml 已提交
480 481
            self._num_groups, self._num_channels, self._epsilon
        )
482

483

Z
zhiboniu 已提交
484
class LayerNorm(Layer):
485
    r"""
L
Ligoml 已提交
486
    Construct a callable object of the ``LayerNorm`` class.
487 488 489 490 491 492 493 494
    For more details, refer to code examples.
    It implements the function of the Layer Normalization Layer and can be applied to mini-batch input data.
    Refer to `Layer Normalization <https://arxiv.org/pdf/1607.06450v1.pdf>`_

    The formula is as follows:

    ..  math::

495
        \mu & = \frac{1}{H}\sum_{i=1}^{H} x_i
496

497
        \sigma & = \sqrt{\frac{1}{H}\sum_{i=1}^{H}{(x_i - \mu)^2} + \epsilon}
498

499
        y & = f(\frac{g}{\sigma}(x - \mu) + b)
500 501 502

    - :math:`x`: the vector representation of the summed inputs to the neurons in that layer.
    - :math:`H`: the number of hidden units in a layers
503
    - :math:`\epsilon`: the small value added to the variance to prevent division by zero.
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    - :math:`g`: the trainable scale parameter.
    - :math:`b`: the trainable bias parameter.

    Parameters:
        normalized_shape(int|list|tuple): Input shape from an expected input of
            size :math:`[*, normalized_shape[0], normalized_shape[1], ..., normalized_shape[-1]]`.
            If it is a single integer, this module will normalize over the last dimension
            which is expected to be of that specific size.
        epsilon(float, optional): The small value added to the variance to prevent
            division by zero. Default: 1e-05.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
            gain :math:`g`. If False, weight is None. If is None, a default :code:`ParamAttr` would be added as scale. The
            :attr:`param_attr` is initialized as 1 if it is added. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
            bias :math:`b`. If is False, bias is None. If is None, a default :code:`ParamAttr` would be added as bias. The
            :attr:`bias_attr` is initialized as 0 if it is added. Default: None.
        name(str, optional): Name for the LayerNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
        - x: 2-D, 3-D, 4-D or 5-D tensor.
        - output: same shape as input x.

    Returns:
        None

    Examples:

        .. code-block:: python

          import paddle

L
Ligoml 已提交
535 536
          x = paddle.rand((2, 2, 2, 3))
          layer_norm = paddle.nn.LayerNorm(x.shape[1:])
537 538
          layer_norm_out = layer_norm(x)

Z
zhang wenhui 已提交
539
          print(layer_norm_out)
540 541
    """

L
Ligoml 已提交
542 543 544 545 546 547 548 549
    def __init__(
        self,
        normalized_shape,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        name=None,
    ):
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
        super(LayerNorm, self).__init__()
        if isinstance(normalized_shape, numbers.Integral):
            normalized_shape = [normalized_shape]

        self._normalized_shape = list(normalized_shape)
        self._epsilon = epsilon
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
        param_shape = [np.prod(self._normalized_shape)]

        if weight_attr is False:
            self.weight = None
        else:
            self.weight = self.create_parameter(
                attr=self._weight_attr,
                shape=param_shape,
L
Ligoml 已提交
566 567
                default_initializer=Constant(1.0),
            )
568 569 570 571

        if bias_attr is False:
            self.bias = None
        else:
L
Ligoml 已提交
572 573 574
            self.bias = self.create_parameter(
                attr=self._bias_attr, shape=param_shape, is_bias=True
            )
575 576

    def forward(self, input):
L
Ligoml 已提交
577 578 579 580 581 582 583
        return layer_norm(
            input,
            normalized_shape=self._normalized_shape,
            weight=self.weight,
            bias=self.bias,
            epsilon=self._epsilon,
        )
584

585
    def extra_repr(self):
L
Ligoml 已提交
586 587 588
        return 'normalized_shape={}, epsilon={}'.format(
            self._normalized_shape, self._epsilon
        )
589

590

Z
zhiboniu 已提交
591
class _BatchNormBase(Layer):
592 593 594 595
    """
    BatchNorm base .
    """

L
Ligoml 已提交
596 597 598 599 600 601 602 603 604 605 606
    def __init__(
        self,
        num_features,
        momentum=0.9,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        data_format='NCHW',
        use_global_stats=None,
        name=None,
    ):
607 608 609 610
        super(_BatchNormBase, self).__init__()
        self._num_features = num_features
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
C
ceci3 已提交
611
        self._use_global_stats = use_global_stats
612 613

        if get_default_dtype() == 'float16':
G
Guoxia Wang 已提交
614 615 616
            self._dtype = 'float32'
        else:
            self._dtype = get_default_dtype()
617 618 619 620

        param_shape = [num_features]

        # create parameter
621 622
        if weight_attr == False:
            self.weight = self.create_parameter(
G
Guoxia Wang 已提交
623 624 625
                attr=None,
                shape=param_shape,
                dtype=self._dtype,
L
Ligoml 已提交
626 627
                default_initializer=Constant(1.0),
            )
628 629 630 631 632
            self.weight.stop_gradient = True
        else:
            self.weight = self.create_parameter(
                attr=self._weight_attr,
                shape=param_shape,
G
Guoxia Wang 已提交
633
                dtype=self._dtype,
L
Ligoml 已提交
634 635 636 637 638 639
                default_initializer=Constant(1.0),
            )
            self.weight.stop_gradient = (
                self._weight_attr != None
                and self._weight_attr.learning_rate == 0.0
            )
640

641
        if bias_attr == False:
L
Ligoml 已提交
642 643 644 645 646 647 648
            self.bias = self.create_parameter(
                attr=None,
                shape=param_shape,
                dtype=self._dtype,
                default_initializer=Constant(0.0),
                is_bias=True,
            )
649 650
            self.bias.stop_gradient = True
        else:
L
Ligoml 已提交
651 652 653 654 655 656 657 658 659
            self.bias = self.create_parameter(
                attr=self._bias_attr,
                shape=param_shape,
                dtype=self._dtype,
                is_bias=True,
            )
            self.bias.stop_gradient = (
                self._bias_attr != None and self._bias_attr.learning_rate == 0.0
            )
660 661 662 663 664 665 666 667

        moving_mean_name = None
        moving_variance_name = None

        if name is not None:
            moving_mean_name = name + "_mean"
            moving_variance_name = name + "_variance"

L
Ligoml 已提交
668 669 670 671 672 673 674 675 676 677
        self._mean = self.create_parameter(
            dtype=self._dtype,
            attr=ParamAttr(
                name=moving_mean_name,
                initializer=Constant(0.0),
                trainable=False,
                do_model_average=True,
            ),
            shape=param_shape,
        )
678 679
        self._mean.stop_gradient = True

L
Ligoml 已提交
680 681 682 683 684 685 686 687 688 689
        self._variance = self.create_parameter(
            dtype=self._dtype,
            attr=ParamAttr(
                name=moving_variance_name,
                initializer=Constant(1.0),
                trainable=False,
                do_model_average=True,
            ),
            shape=param_shape,
        )
690 691 692 693 694 695 696
        self._variance.stop_gradient = True

        self._data_format = data_format
        self._in_place = False
        self._momentum = momentum
        self._epsilon = epsilon
        self._fuse_with_relu = False
697
        self._name = name
698 699 700 701

    def _check_input_dim(self, input):
        raise NotImplementedError("BatchNorm Base error")

702 703 704
    def _check_data_format(self, input):
        raise NotImplementedError("BatchNorm Base data format error")

705 706
    def forward(self, input):

707 708
        self._check_data_format(self._data_format)

709 710
        self._check_input_dim(input)

711
        if self.training:
712
            warnings.warn(
L
Ligoml 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
                "When training, we now always track global mean and variance."
            )

        return batch_norm(
            input,
            self._mean,
            self._variance,
            weight=self.weight,
            bias=self.bias,
            training=self.training,
            momentum=self._momentum,
            epsilon=self._epsilon,
            data_format=self._data_format,
            use_global_stats=self._use_global_stats,
        )
728

729 730
    def extra_repr(self):
        main_str = 'num_features={}, momentum={}, epsilon={}'.format(
L
Ligoml 已提交
731 732
            self._num_features, self._momentum, self._epsilon
        )
733
        if self._data_format != 'NCHW':
734 735 736 737 738
            main_str += ', data_format={}'.format(self._data_format)
        if self._name is not None:
            main_str += ', name={}'.format(self._name)
        return main_str

739

C
cnn 已提交
740
class BatchNorm1D(_BatchNormBase):
741
    r"""
742 743
    Applies Batch Normalization over a 2D or 3D input (a mini-batch of 1D inputswith additional channel dimension) as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift .

744 745
    When use_global_stats = False, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
746 747 748 749
    Calculated as follows:

    ..  math::

750 751 752 753
        \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\
        \ mini-batch\ mean \\
        \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \
        \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\
754

755 756
    When use_global_stats = True, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are not the statistics of one mini-batch.
757 758 759 760
    They are global or running statistics (moving_mean and moving_variance). It usually got from the
    pre-trained model. Calculated as follows:

    .. math::
761 762
        moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\
        moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\
763 764 765 766 767

    The normalization function formula is as follows:

    ..  math::

768 769
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
770

771 772 773
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable proportional parameter
    - :math:`\beta` : trainable deviation parameter
774 775 776 777 778 779 780 781

    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
            of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable.
782
            If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None.
783 784 785 786
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm.
            If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable.
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
787
        data_format(str, optional): Specify the input data format, may be "NC", "NCL" or "NLC". Default "NCL".
C
ceci3 已提交
788
        use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None.
789 790 791
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
F
Feiyu Chan 已提交
792 793
        - x: 2-D or 3-D tensor with shape: (batch, num_features) or (batch, num_features, length) when data_format is "NC" or "NCL",
            (batch, length, num_features) when data_format is "NLC".
794 795 796 797 798 799 800 801 802 803 804
        - output: 3-D tensor with same shape as input x.

    Returns:
        None.
    

    Examples:
        .. code-block:: python

          import paddle

L
Ligoml 已提交
805
          x = paddle.rand((2, 1, 3))
C
cnn 已提交
806
          batch_norm = paddle.nn.BatchNorm1D(1)
807 808
          batch_norm_out = batch_norm(x)

Z
zhang wenhui 已提交
809
          print(batch_norm_out)
810 811
    """

L
Ligoml 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
    def __init__(
        self,
        num_features,
        momentum=0.9,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        data_format='NCL',
        use_global_stats=None,
        name=None,
    ):
        super(BatchNorm1D, self).__init__(
            num_features,
            momentum,
            epsilon,
            weight_attr,
            bias_attr,
            data_format,
            use_global_stats,
            name,
        )
C
ceci3 已提交
833

834 835 836
    def _check_data_format(self, input):
        if input == 'NCHW' or input == 'NC' or input == 'NCL':
            self._data_format = 'NCHW'
F
Feiyu Chan 已提交
837 838
        elif input == "NHWC" or input == 'NLC':
            self._data_format = "NHWC"
839
        else:
F
Feiyu Chan 已提交
840
            raise ValueError(
L
Ligoml 已提交
841 842
                'expected NC , NCL, NLC or None for data_format input'
            )
843

844 845
    def _check_input_dim(self, input):
        if len(input.shape) != 2 and len(input.shape) != 3:
L
Ligoml 已提交
846 847 848 849 850
            raise ValueError(
                'expected 2D or 3D input (got {}D input)'.format(
                    len(input.shape)
                )
            )
851 852


C
cnn 已提交
853
class BatchNorm2D(_BatchNormBase):
854
    r"""
855 856
    Applies Batch Normalization over a 4D input (a mini-batch of 2D inputswith additional channel dimension) as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift .

857 858
    When use_global_stats = False, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
859 860 861 862
    Calculated as follows:

    ..  math::

863 864 865 866
        \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//
        \ mini-batch\ mean \\
        \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - 
        \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\
867

868 869
    When use_global_stats = True, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are not the statistics of one mini-batch.
870 871 872 873
    They are global or running statistics (moving_mean and moving_variance). It usually got from the
    pre-trained model. Calculated as follows:

    .. math::
874 875
        moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\
        moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\
876 877 878 879 880

    The normalization function formula is as follows:

    ..  math::

881 882
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
883

884 885 886
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable proportional parameter
    - :math:`\beta` : trainable deviation parameter
887 888 889 890 891 892 893 894

    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
            of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable.
895
            If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None.
896 897 898 899
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm.
            If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable.
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
F
Feiyu Chan 已提交
900
        data_format(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC". Default: NCHW.
C
ceci3 已提交
901
        use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None.
902 903 904
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
F
Feiyu Chan 已提交
905 906
        - x: 4-D tensor with shape: (batch, num_features, height, weight) when data_format is "NCHW",
            or (batch, height, weight, num_features) when data_format is "NHWC".
907 908 909 910 911 912 913 914 915 916
        - output: 4-D tensor with same shape as input x.

    Returns:
        None

    Examples:
        .. code-block:: python

          import paddle

L
Ligoml 已提交
917
          x = paddle.rand((2, 1, 2, 3))
C
cnn 已提交
918
          batch_norm = paddle.nn.BatchNorm2D(1)
919 920
          batch_norm_out = batch_norm(x)

Z
zhang wenhui 已提交
921
          print(batch_norm_out)
922 923
    """

924
    def _check_data_format(self, input):
925
        if input == 'NCHW':
926
            self._data_format = input
F
Feiyu Chan 已提交
927 928
        elif input == "NHWC":
            self._data_format = input
929
        else:
F
Feiyu Chan 已提交
930
            raise ValueError('expected NCHW or NHWC for data_format input')
931

932 933
    def _check_input_dim(self, input):
        if len(input.shape) != 4:
L
Ligoml 已提交
934 935 936
            raise ValueError(
                'expected 4D input (got {}D input)'.format(len(input.shape))
            )
937 938


C
cnn 已提交
939
class BatchNorm3D(_BatchNormBase):
940
    r"""
941 942
    Applies Batch Normalization over a 5D input (a mini-batch of 3D inputswith additional channel dimension) as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift .

943 944
    When use_global_stats = False, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
945 946 947 948
    Calculated as follows:

    ..  math::

949 950 951 952
        \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\
        \ mini-batch\ mean \\
        \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \
        \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\
953

C
ceci3 已提交
954
    When use_global_stats = True, the :math:`\\mu_{\\beta}`
955 956 957 958 959
    and :math:`\\sigma_{\\beta}^{2}` are not the statistics of one mini-batch.
    They are global or running statistics (moving_mean and moving_variance). It usually got from the
    pre-trained model. Calculated as follows:

    .. math::
960 961
        moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\
        moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\
962 963 964 965 966

    The normalization function formula is as follows:

    ..  math::

967 968
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
969

970 971 972
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable proportional parameter
    - :math:`\beta` : trainable deviation parameter
973 974 975 976 977 978 979 980

    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
            of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable.
981
            If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None.
982 983 984 985
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm.
            If it is set to None or one attribute of ParamAttr, batch_norm
            will create ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable.
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
F
Feiyu Chan 已提交
986
        data_format(str, optional): Specify the input data format, the data format can be "NCDHW" or "NDHWC. Default: NCDHW.
C
ceci3 已提交
987
        use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None.
988 989 990
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
F
Feiyu Chan 已提交
991 992
        - x: 5-D tensor with shape: (batch, num_features, dims, height, weight) when data_format is "NCDHW",
            or (batch, dims, height, weight, num_features) when data_format is "NDHWC".
993 994 995 996 997 998 999 1000 1001 1002
        - output: 5-D tensor with same shape as input x.

    Returns:
        None

    Examples:
        .. code-block:: python

          import paddle

L
Ligoml 已提交
1003
          x = paddle.rand((2, 1, 2, 2, 3))
C
cnn 已提交
1004
          batch_norm = paddle.nn.BatchNorm3D(1)
1005 1006
          batch_norm_out = batch_norm(x)

Z
zhang wenhui 已提交
1007
          print(batch_norm_out)
1008 1009
    """

L
Ligoml 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    def __init__(
        self,
        num_features,
        momentum=0.9,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        data_format='NCDHW',
        use_global_stats=None,
        name=None,
    ):
        super(BatchNorm3D, self).__init__(
            num_features,
            momentum,
            epsilon,
            weight_attr,
            bias_attr,
            data_format,
            use_global_stats,
            name,
        )
C
ceci3 已提交
1031

1032 1033 1034
    def _check_data_format(self, input):
        if input == 'NCHW' or input == 'NCDHW':
            self._data_format = 'NCHW'
F
Feiyu Chan 已提交
1035 1036
        elif input == "NHWC" or input == "NDHWC":
            self._data_format = 'NHWC'
1037
        else:
F
Feiyu Chan 已提交
1038
            raise ValueError(
L
Ligoml 已提交
1039 1040
                'expected NCDHW, NDHWC or None for data_format input'
            )
1041

1042 1043
    def _check_input_dim(self, input):
        if len(input.shape) != 5:
L
Ligoml 已提交
1044 1045 1046
            raise ValueError(
                'expected 5D input (got {}D input)'.format(len(input.shape))
            )
1047 1048


1049
class SyncBatchNorm(_BatchNormBase):
1050
    r"""
1051

C
ceci3 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    This interface is used to construct a callable object of the ``SyncBatchNorm`` class.
    It implements the function of the Cross-GPU Synchronized Batch Normalization Layer, and can 
    be used as a normalizer function for other operations, such as conv2d and fully connected 
    operations.
    The data is normalized by the mean and variance of the channel based on whole mini-batch
    , which including data in all gpus.
    Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing
    Internal Covariate Shift <https://arxiv.org/pdf/1502.03167.pdf>`_
    for more details.

    When model in training mode, the :math:`\\mu_{\\beta}` 
    and :math:`\\sigma_{\\beta}^{2}` are the statistics of whole mini-batch data in all gpus.
    Calculated as follows:

    ..  math::

1068 1069 1070 1071
        \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\
        \ mini-batch\ mean \\
        \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \
        \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\
C
ceci3 已提交
1072 1073 1074 1075 1076

    - :math:`x` : whole mini-batch data in all gpus
    - :math:`m` : the size of the whole mini-batch data

    When model in evaluation mode, the :math:`\\mu_{\\beta}`
1077
    and :math:`\sigma_{\beta}^{2}` are global statistics (moving_mean and moving_variance, 
C
ceci3 已提交
1078 1079 1080
    which usually got from the pre-trained model). Global statistics calculated as follows:

    .. math::
1081 1082
        moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\
        moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\
C
ceci3 已提交
1083 1084 1085 1086 1087

    The formula of normalization is as follows:
 
    ..  math::

1088 1089 1090
        \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\
        \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\
        y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift
C
ceci3 已提交
1091

1092 1093 1094
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable scale parameter vector
    - :math:`\beta` : trainable shift parameter vector 
C
ceci3 已提交
1095

1096
    Note:
1097 1098 1099
        If you want to use container to pack your model and has :ref:`api_paddle_nn_SyncBatchNorm` in the
        evaluation phase, please use :ref:`api_paddle_nn_LayerList` or :ref:`api_paddle_nn_Sequential` instead of
        :ref:`api_paddle_hub_list` to pack the model.
1100

C
ceci3 已提交
1101 1102 1103 1104 1105 1106 1107
    Parameters:
        num_features(int): Indicate the number of channels of the input ``Tensor``.
        epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
        momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
        weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale`
             of this layer. If it is set to None or one attribute of ParamAttr, this layerr
             will create ParamAttr as param_attr. If the Initializer of the param_attr
1108
             is not set, the parameter is initialized with ones. If it is set to False, 
C
ceci3 已提交
1109 1110 1111 1112 1113 1114 1115 1116
             this layer will not have trainable scale parameter. Default: None.
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of this layer.
             If it is set to None or one attribute of ParamAttr, this layer
             will create ParamAttr as bias_attr. If the Initializer of the bias_attr
             is not set, the bias is initialized zero. If it is set to False, this layer will not 
             have trainable bias parameter. Default: None.

    Shapes:
1117 1118
        - input: Tensor that the dimension from 2 to 5.
        - output: Tensor with the same shape as input.
C
ceci3 已提交
1119 1120 1121 1122

    Examples:
        .. code-block:: python

1123
            # required: gpu
1124

1125 1126
            import paddle
            import paddle.nn as nn
C
ceci3 已提交
1127

1128
            x = paddle.to_tensor([[[[0.3, 0.4], [0.3, 0.07]], [[0.83, 0.37], [0.18, 0.93]]]]).astype('float32')
C
ceci3 已提交
1129

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
            if paddle.is_compiled_with_cuda():
                sync_batch_norm = nn.SyncBatchNorm(2)
                hidden1 = sync_batch_norm(x)
                print(hidden1)
                # Tensor(shape=[1, 2, 2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False,
                #        [[[[ 0.26824948,  1.09363246],
                #           [ 0.26824948, -1.63013160]],

                #          [[ 0.80956620, -0.66528702],
                #           [-1.27446556,  1.13018656]]]])
1140

C
ceci3 已提交
1141 1142
    """

L
Ligoml 已提交
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    def __init__(
        self,
        num_features,
        momentum=0.9,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        data_format='NCHW',
        name=None,
    ):
        super(SyncBatchNorm, self).__init__(
            num_features,
            momentum,
            epsilon,
            weight_attr,
            bias_attr,
            data_format,
            None,
            name,
        )
C
ceci3 已提交
1163

C
ceci3 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    def _check_data_format(self):
        if self._data_format in ['NCHW', 'NCDHW', 'NC', 'NCL']:
            self._data_format = 'NCHW'
        elif self._data_format in ["NHWC", "NDHWC", 'NLC']:
            self._data_format = 'NHWC'
        else:
            raise ValueError(
                'expected \'NCDHW\', \'NDHWC\', \'NCL\', \'NLC\', \'NC\', \'NCHW\', \'NHWC\' for data_format'
            )

C
ceci3 已提交
1174
    def forward(self, x):
C
ceci3 已提交
1175
        self._check_data_format()
C
ceci3 已提交
1176 1177 1178 1179 1180 1181 1182 1183
        # 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

        ### train mode: use mini-batch stats, eval mode: use global stats
        ### use_global_stats only support False in sync_batch_norm
1184
        if in_dygraph_mode():
1185
            sync_batch_norm_out, _, _, _, _, _ = _C_ops.sync_batch_norm_(
L
Ligoml 已提交
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
                x,
                self.weight,
                self.bias,
                self._mean,
                self._variance,
                self._momentum,
                self._epsilon,
                self._data_format,
                not self.training,
                False,
                False,
                False,
            )
1199 1200 1201
            return sync_batch_norm_out

        elif in_dynamic_mode():
L
Ligoml 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
            attrs = (
                "momentum",
                self._momentum,
                "epsilon",
                self._epsilon,
                "is_test",
                not self.training,
                "data_layout",
                self._data_format,
                "use_mkldnn",
                False,
                "fuse_with_relu",
                False,
                "use_global_stats",
                False,
                'trainable_statistics',
                False,
            )
1220
            sync_batch_norm_out, _, _, _, _, _ = _legacy_C_ops.sync_batch_norm(
L
Ligoml 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229
                x,
                self.weight,
                self.bias,
                self._mean,
                self._variance,
                mean_out,
                variance_out,
                *attrs
            )
C
ceci3 已提交
1230 1231
            return sync_batch_norm_out

L
Ligoml 已提交
1232 1233 1234
        check_variable_and_dtype(
            x, 'input', ['float16', 'float32', 'float64'], 'SyncBatchNorm'
        )
C
ceci3 已提交
1235 1236 1237 1238 1239

        attrs = {
            "momentum": self._momentum,
            "epsilon": self._epsilon,
            "is_test": not self.training,
1240
            "data_layout": self._data_format,
C
ceci3 已提交
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
            "use_mkldnn": False,
            "fuse_with_relu": False,
            "use_global_stats": False,
            "trainable_statistics": False,
        }

        inputs = {
            "X": [x],
            "Scale": [self.weight],
            "Bias": [self.bias],
            "Mean": [self._mean],
L
Ligoml 已提交
1252
            "Variance": [self._variance],
C
ceci3 已提交
1253 1254 1255
        }

        saved_mean = self._helper.create_variable_for_type_inference(
L
Ligoml 已提交
1256 1257
            dtype=self._dtype, stop_gradient=True
        )
C
ceci3 已提交
1258
        saved_variance = self._helper.create_variable_for_type_inference(
L
Ligoml 已提交
1259 1260
            dtype=self._dtype, stop_gradient=True
        )
C
ceci3 已提交
1261
        sync_batch_norm_out = self._helper.create_variable_for_type_inference(
L
Ligoml 已提交
1262 1263
            self._dtype
        )
C
ceci3 已提交
1264 1265 1266 1267 1268 1269

        outputs = {
            "Y": [sync_batch_norm_out],
            "MeanOut": [mean_out],
            "VarianceOut": [variance_out],
            "SavedMean": [saved_mean],
L
Ligoml 已提交
1270
            "SavedVariance": [saved_variance],
C
ceci3 已提交
1271 1272
        }

L
Ligoml 已提交
1273 1274 1275
        self._helper.append_op(
            type="sync_batch_norm", inputs=inputs, outputs=outputs, attrs=attrs
        )
C
ceci3 已提交
1276
        return sync_batch_norm_out
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

    @classmethod
    def convert_sync_batchnorm(cls, layer):
        """
        Helper function to convert :class: `paddle.nn.BatchNorm*d` layers in the model to :class: `paddle.nn.SyncBatchNorm` layers.

        Parameters:
            layer(paddle.nn.Layer): model containing one or more `BatchNorm*d` layers.

        Returns:
            The original model with converted SyncBatchNorm layers. If BatchNorm*d layer in the model, use SyncBatchNorm layer instead.

        Examples:
            .. code-block:: python
1291

1292 1293 1294
                import paddle
                import paddle.nn as nn

C
cnn 已提交
1295
                model = nn.Sequential(nn.Conv2D(3, 5, 3), nn.BatchNorm2D(5))
1296 1297 1298 1299 1300
                sync_model = nn.SyncBatchNorm.convert_sync_batchnorm(model)

        """
        layer_output = layer
        if isinstance(layer, _BatchNormBase):
L
Ligoml 已提交
1301 1302 1303 1304 1305
            if (
                layer._weight_attr != None
                and not isinstance(layer._weight_attr, bool)
                and layer._weight_attr.name != None
            ):
C
ceci3 已提交
1306
                layer._weight_attr.name = layer._weight_attr.name + '_sync'
L
Ligoml 已提交
1307 1308 1309 1310 1311
            if (
                layer._bias_attr != None
                and not isinstance(layer._bias_attr, bool)
                and layer._bias_attr.name != None
            ):
C
ceci3 已提交
1312 1313
                layer._bias_attr.name = layer._bias_attr.name + '_sync'

L
Ligoml 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322
            layer_output = SyncBatchNorm(
                layer._num_features,
                layer._momentum,
                layer._epsilon,
                layer._weight_attr,
                layer._bias_attr,
                layer._data_format,
                layer._name,
            )
1323 1324 1325 1326 1327 1328 1329 1330

            if layer._weight_attr != False and layer._bias_attr != False:
                with no_grad():
                    layer_output.weight = layer.weight
                    layer_output.bias = layer.bias
            layer_output._mean = layer._mean
            layer_output._variance = layer._variance

C
ceci3 已提交
1331
        for name, sublayer in layer.named_children():
L
Ligoml 已提交
1332 1333 1334
            layer_output.add_sublayer(
                name, cls.convert_sync_batchnorm(sublayer)
            )
1335 1336
        del layer
        return layer_output
1337 1338


Z
zhiboniu 已提交
1339
class LocalResponseNorm(Layer):
1340
    """
L
Ligoml 已提交
1341 1342
    Local Response Normalization performs a type of "lateral inhibition" by normalizing over local input regions.
    For more information, please refer to `ImageNet Classification with Deep Convolutional Neural Networks <https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf>`_
1343

L
Ligoml 已提交
1344
    See more details in :ref:`api_paddle_nn_functional_local_response_norm` .
1345

L
Ligoml 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    Parameters:
        size (int): The number of channels to sum over.
        alpha (float, optional): The scaling parameter, positive. Default:1e-4
        beta (float, optional): The exponent, positive. Default:0.75
        k (float, optional): An offset, positive. Default: 1.0
        data_format (str, optional): Specify the data format of the input, and the data format of the output
            will be consistent with that of the input. An optional string from:
            If input is 3-D Tensor, the string could be `"NCL"` or `"NLC"` . When it is `"NCL"`,
            the data is stored in the order of: `[batch_size, input_channels, feature_length]`.
            If input is 4-D Tensor, the string could be  `"NCHW"`, `"NHWC"`. When it is `"NCHW"`,
            the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`.
            If input is 5-D Tensor, the string could be  `"NCDHW"`, `"NDHWC"` . When it is `"NCDHW"`,
            the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
        name (str, optional): Name for the operation (optional, default is None). For more information,
            please refer to :ref:`api_guide_Name`.
1361

L
Ligoml 已提交
1362 1363 1364
    Shape:
        - input: 3-D/4-D/5-D tensor.
        - output: 3-D/4-D/5-D tensor, the same shape as input.
1365

L
Ligoml 已提交
1366
    Examples:
1367

L
Ligoml 已提交
1368
    .. code-block:: python
1369

L
Ligoml 已提交
1370 1371 1372 1373 1374 1375 1376
        import paddle

        x = paddle.rand(shape=(3, 3, 112, 112), dtype="float32")
        m = paddle.nn.LocalResponseNorm(size=5)
        y = m(x)
        print(y.shape)  # [3, 3, 112, 112]
    """
1377

L
Ligoml 已提交
1378 1379 1380 1381 1382 1383 1384 1385 1386
    def __init__(
        self,
        size,
        alpha=0.0001,
        beta=0.75,
        k=1.0,
        data_format="NCHW",
        name=None,
    ):
1387 1388 1389 1390 1391 1392 1393 1394 1395
        super(LocalResponseNorm, self).__init__()
        self.size = size
        self.alpha = alpha
        self.beta = beta
        self.k = k
        self.data_format = data_format
        self.name = name

    def forward(self, input):
L
Ligoml 已提交
1396 1397 1398 1399 1400 1401 1402 1403 1404
        out = F.local_response_norm(
            input,
            self.size,
            self.alpha,
            self.beta,
            self.k,
            self.data_format,
            self.name,
        )
1405
        return out
1406 1407 1408

    def extra_repr(self):
        main_str = 'size={}, alpha={}, beta={}, k={}'.format(
L
Ligoml 已提交
1409 1410
            self.size, self.alpha, self.beta, self.k
        )
1411
        if self.data_format != 'NCHW':
1412 1413 1414 1415
            main_str += ', data_format={}'.format(self.data_format)
        if self.name is not None:
            main_str += ', name={}'.format(self.name)
        return main_str