norm.py 53.4 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

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

33
from ...framework import get_default_dtype
C
ceci3 已提交
34

Z
zhiboniu 已提交
35 36
from ..initializer import Constant
from ...framework import ParamAttr
37
from ...fluid.data_feeder import check_variable_and_dtype
38 39 40 41 42 43

from ..functional import batch_norm, layer_norm, instance_norm

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

51 52
__all__ = []

C
ceci3 已提交
53

Z
zhiboniu 已提交
54
class _InstanceNormBase(Layer):
55
    """
56
    This class is based class for InstanceNorm1D, 2d, 3d.
57

C
cnn 已提交
58
    See InstaceNorm1D, InstanceNorm2D or InstanceNorm3D for more details.
59 60
    """

61 62 63 64 65 66 67 68 69 70
    def __init__(
        self,
        num_features,
        epsilon=1e-5,
        momentum=0.9,
        weight_attr=None,
        bias_attr=None,
        data_format="NCHW",
        name=None,
    ):
71
        super().__init__()
72

73
        if weight_attr is False or bias_attr is False:
74 75
            assert (
                weight_attr == bias_attr
76
            ), "weight_attr and bias_attr must be set to False at the same time in InstanceNorm"
77 78 79
        self._epsilon = epsilon
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
80
        self._num_features = num_features
81

82
        if weight_attr is not False and bias_attr is not False:
83 84 85 86
            self.scale = self.create_parameter(
                attr=self._weight_attr,
                shape=[num_features],
                default_initializer=Constant(1.0),
87 88 89 90 91 92 93 94
                is_bias=False,
            )
            self.bias = self.create_parameter(
                attr=self._bias_attr,
                shape=[num_features],
                default_initializer=Constant(0.0),
                is_bias=True,
            )
95 96 97 98 99 100 101 102 103 104
        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)

105 106 107
        return instance_norm(
            input, weight=self.scale, bias=self.bias, eps=self._epsilon
        )
108

109
    def extra_repr(self):
110 111 112
        return 'num_features={}, epsilon={}'.format(
            self._num_features, self._epsilon
        )
113

114

C
cnn 已提交
115
class InstanceNorm1D(_InstanceNormBase):
116
    r"""
117
    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 .
118 119 120 121 122 123

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

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

    ..  math::
124

125 126 127 128 129 130 131
        \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
132

133
Where `H` means height of feature map, `W` means width of feature map.
134 135 136 137 138 139 140

    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`
141 142 143 144
            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.
145
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm.
146 147 148 149
            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.
150
        data_format(str, optional): Specify the input data format, may be "NC", "NCL". Default "NCL".
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
        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

168
          x = paddle.rand((2, 2, 3))
C
cnn 已提交
169
          instance_norm = paddle.nn.InstanceNorm1D(2)
170 171
          instance_norm_out = instance_norm(x)

Z
zhang wenhui 已提交
172
          print(instance_norm_out)
173 174 175 176 177

    """

    def _check_input_dim(self, input):
        if len(input.shape) != 2 and len(input.shape) != 3:
178 179 180 181 182
            raise ValueError(
                'expected 2D or 3D input (got {}D input)'.format(
                    len(input.shape)
                )
            )
183 184


C
cnn 已提交
185
class InstanceNorm2D(_InstanceNormBase):
186
    r"""
187
    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 .
188 189 190 191 192 193 194

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


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

    ..  math::
195

196 197 198 199 200 201 202
        \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
203

204
Where `H` means height of feature map, `W` means width of feature map.
205 206 207 208 209 210 211

    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`
212 213 214 215
            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.
216
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm.
217 218 219 220
            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.
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        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

236
            import paddle
237

238 239 240
            x = paddle.rand((2, 2, 2, 3))
            instance_norm = paddle.nn.InstanceNorm2D(2)
            instance_norm_out = instance_norm(x)
241

242
            print(instance_norm_out)
243 244 245 246
    """

    def _check_input_dim(self, input):
        if len(input.shape) != 4:
247 248 249
            raise ValueError(
                'expected 4D input (got {}D input)'.format(len(input.shape))
            )
250 251


C
cnn 已提交
252
class InstanceNorm3D(_InstanceNormBase):
253
    r"""
254
    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 .
255 256 257 258 259 260 261

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


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

    ..  math::
262

263 264 265 266 267 268 269
        \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
270

271
Where `H` means height of feature map, `W` means width of feature map.
272 273 274 275 276 277 278

    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`
279 280 281 282
            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.
283
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm.
284 285 286 287
            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.
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
        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

303
            import paddle
304

305 306 307
            x = paddle.rand((2, 2, 2, 2, 3))
            instance_norm = paddle.nn.InstanceNorm3D(2)
            instance_norm_out = instance_norm(x)
308

309
            print(instance_norm_out.numpy)
310 311 312 313
    """

    def _check_input_dim(self, input):
        if len(input.shape) != 5:
314 315 316
            raise ValueError(
                'expected 5D input (got {}D input)'.format(len(input.shape))
            )
317 318


Z
zhiboniu 已提交
319
class GroupNorm(Layer):
320
    """
321

322 323 324 325 326 327 328
    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.
329
        num_channels(int): The number of channels of input.
330
        epsilon(float, optional): The small value added to the variance to prevent
331
            division by zero. Default: 1e-05.
332
        weight_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
333 334
            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.
335
        bias_attr(ParamAttr|bool, optional): The parameter attribute for the learnable
336 337
            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.
338 339 340 341
        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:
342
        - x: Tensor with shape: attr:`(batch, num_features, *)`.
343
        - output: The same shape as input x.
344 345 346 347 348 349

    Returns:
        None

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

351
            import paddle
352

353
            x = paddle.arange(48, dtype="float32").reshape((2, 6, 2, 2))
354 355
            group_norm = paddle.nn.GroupNorm(num_channels=6, num_groups=6)
            group_norm_out = group_norm(x)
356

357
            print(group_norm_out)
358 359
    """

360 361 362 363 364 365 366 367 368 369
    def __init__(
        self,
        num_groups,
        num_channels,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        data_format='NCHW',
        name=None,
    ):
370
        super().__init__()
371 372 373 374 375
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
        self._epsilon = epsilon
        self._num_channels = num_channels
        self._num_groups = num_groups
376
        if data_format not in ['NCHW', 'NHWC']:
377
            raise ValueError("unsupported data layout:" + data_format)
378
        self._data_format = data_format
379 380 381

        param_shape = [self._num_channels]

382
        if weight_attr is False:
383
            self.weight = self.create_parameter(
384 385
                attr=None, shape=param_shape, default_initializer=Constant(1.0)
            )
386 387 388 389 390
            self.weight.stop_gradient = True
        else:
            self.weight = self.create_parameter(
                attr=self._weight_attr,
                shape=param_shape,
391 392 393
                default_initializer=Constant(1.0),
            )
            self.weight.stop_gradient = (
394
                self._weight_attr is not None
395 396
                and self._weight_attr.learning_rate == 0.0
            )
397

398
        if bias_attr is False:
399 400 401 402 403 404
            self.bias = self.create_parameter(
                attr=None,
                shape=param_shape,
                default_initializer=Constant(0.0),
                is_bias=True,
            )
405 406
            self.bias.stop_gradient = True
        else:
407 408 409 410
            self.bias = self.create_parameter(
                attr=self._bias_attr, shape=param_shape, is_bias=True
            )
            self.bias.stop_gradient = (
411 412
                self._bias_attr is not None
                and self._bias_attr.learning_rate == 0.0
413
            )
414 415

    def forward(self, input):
416
        if in_dygraph_mode():
417
            return _C_ops.group_norm(
418 419 420 421 422
                input,
                self.weight,
                self.bias,
                self._epsilon,
                self._num_groups,
423
                self._data_format,
424
            )
425

426 427 428 429 430 431
        mean_out = self._helper.create_variable_for_type_inference(
            dtype=input.dtype, stop_gradient=True
        )
        variance_out = self._helper.create_variable_for_type_inference(
            dtype=input.dtype, stop_gradient=True
        )
432

433
        if _in_legacy_dygraph():
434
            pre_act, _, _ = _legacy_C_ops.group_norm(
435 436 437 438 439 440 441 442
                input,
                self.weight,
                self.bias,
                mean_out,
                variance_out,
                'epsilon',
                self._epsilon,
                'groups',
443 444
                self._num_groups,
            )
445
            return pre_act
446

447 448 449 450 451 452 453 454
        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(
455 456 457 458 459 460 461 462 463 464 465 466 467
            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},
        )
468 469 470

        return self._helper.append_activation(group_norm_out, None)

471 472
    def extra_repr(self):
        return 'num_groups={}, num_channels={}, epsilon={}'.format(
473 474
            self._num_groups, self._num_channels, self._epsilon
        )
475

476

Z
zhiboniu 已提交
477
class LayerNorm(Layer):
478
    r"""
479
    Construct a callable object of the ``LayerNorm`` class.
480 481 482 483 484 485 486 487
    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::

488
        \mu & = \frac{1}{H}\sum_{i=1}^{H} x_i
489

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

492
        y & = f(\frac{g}{\sigma}(x - \mu) + b)
493 494 495

    - :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
496
    - :math:`\epsilon`: the small value added to the variance to prevent division by zero.
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
    - :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

528 529
          x = paddle.rand((2, 2, 2, 3))
          layer_norm = paddle.nn.LayerNorm(x.shape[1:])
530 531
          layer_norm_out = layer_norm(x)

Z
zhang wenhui 已提交
532
          print(layer_norm_out)
533 534
    """

535 536 537 538 539 540 541 542
    def __init__(
        self,
        normalized_shape,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        name=None,
    ):
543
        super().__init__()
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
        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,
559 560
                default_initializer=Constant(1.0),
            )
561 562 563 564

        if bias_attr is False:
            self.bias = None
        else:
565 566 567
            self.bias = self.create_parameter(
                attr=self._bias_attr, shape=param_shape, is_bias=True
            )
568 569

    def forward(self, input):
570 571 572 573 574 575 576
        return layer_norm(
            input,
            normalized_shape=self._normalized_shape,
            weight=self.weight,
            bias=self.bias,
            epsilon=self._epsilon,
        )
577

578
    def extra_repr(self):
579 580 581
        return 'normalized_shape={}, epsilon={}'.format(
            self._normalized_shape, self._epsilon
        )
582

583

Z
zhiboniu 已提交
584
class _BatchNormBase(Layer):
585 586 587 588
    """
    BatchNorm base .
    """

589 590 591 592 593 594 595 596 597 598 599
    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,
    ):
600
        super().__init__()
601 602 603
        self._num_features = num_features
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
C
ceci3 已提交
604
        self._use_global_stats = use_global_stats
605 606

        if get_default_dtype() == 'float16':
G
Guoxia Wang 已提交
607 608 609
            self._dtype = 'float32'
        else:
            self._dtype = get_default_dtype()
610 611 612 613

        param_shape = [num_features]

        # create parameter
614
        if weight_attr is False:
615
            self.weight = self.create_parameter(
G
Guoxia Wang 已提交
616 617 618
                attr=None,
                shape=param_shape,
                dtype=self._dtype,
619 620
                default_initializer=Constant(1.0),
            )
621 622 623 624 625
            self.weight.stop_gradient = True
        else:
            self.weight = self.create_parameter(
                attr=self._weight_attr,
                shape=param_shape,
G
Guoxia Wang 已提交
626
                dtype=self._dtype,
627 628 629
                default_initializer=Constant(1.0),
            )
            self.weight.stop_gradient = (
630
                self._weight_attr is not None
631 632
                and self._weight_attr.learning_rate == 0.0
            )
633

634
        if bias_attr is False:
635 636 637 638 639 640 641
            self.bias = self.create_parameter(
                attr=None,
                shape=param_shape,
                dtype=self._dtype,
                default_initializer=Constant(0.0),
                is_bias=True,
            )
642 643
            self.bias.stop_gradient = True
        else:
644 645 646 647 648 649 650
            self.bias = self.create_parameter(
                attr=self._bias_attr,
                shape=param_shape,
                dtype=self._dtype,
                is_bias=True,
            )
            self.bias.stop_gradient = (
651 652
                self._bias_attr is not None
                and self._bias_attr.learning_rate == 0.0
653
            )
654 655 656 657 658 659 660 661

        moving_mean_name = None
        moving_variance_name = None

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

662 663 664 665 666 667 668 669 670 671
        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,
        )
672 673
        self._mean.stop_gradient = True

674 675 676 677 678 679 680 681 682 683
        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,
        )
684 685 686 687 688 689 690
        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
691
        self._name = name
692 693 694 695

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

696 697 698
    def _check_data_format(self, input):
        raise NotImplementedError("BatchNorm Base data format error")

699 700
    def forward(self, input):

701 702
        self._check_data_format(self._data_format)

703 704
        self._check_input_dim(input)

705
        if self.training:
706
            warnings.warn(
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
                "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,
        )
722

723 724
    def extra_repr(self):
        main_str = 'num_features={}, momentum={}, epsilon={}'.format(
725 726
            self._num_features, self._momentum, self._epsilon
        )
727
        if self._data_format != 'NCHW':
728 729 730 731 732
            main_str += ', data_format={}'.format(self._data_format)
        if self._name is not None:
            main_str += ', name={}'.format(self._name)
        return main_str

733

C
cnn 已提交
734
class BatchNorm1D(_BatchNormBase):
735
    r"""
736 737
    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 .

738 739
    When use_global_stats = False, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
740 741 742 743
    Calculated as follows:

    ..  math::

744 745 746 747
        \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 \\
748

749 750
    When use_global_stats = True, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are not the statistics of one mini-batch.
751 752 753 754
    They are global or running statistics (moving_mean and moving_variance). It usually got from the
    pre-trained model. Calculated as follows:

    .. math::
755 756
        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 \\
757 758 759 760 761

    The normalization function formula is as follows:

    ..  math::

762 763
        \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
764

765 766 767
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable proportional parameter
    - :math:`\beta` : trainable deviation parameter
768 769 770 771 772 773 774

    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
775
            will create ParamAttr as weight_attr. If it is set to False, the weight is not learnable.
776
            If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None.
777 778
        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
779
            will create ParamAttr as bias_attr. If it is set to False, the weight is not learnable.
780
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
781
        data_format(str, optional): Specify the input data format, may be "NC", "NCL" or "NLC". Default "NCL".
C
ceci3 已提交
782
        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.
783 784 785
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
F
Feiyu Chan 已提交
786 787
        - 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".
788 789 790 791
        - output: 3-D tensor with same shape as input x.

    Returns:
        None.
792

793 794 795 796 797 798

    Examples:
        .. code-block:: python

          import paddle

799
          x = paddle.rand((2, 1, 3))
C
cnn 已提交
800
          batch_norm = paddle.nn.BatchNorm1D(1)
801 802
          batch_norm_out = batch_norm(x)

Z
zhang wenhui 已提交
803
          print(batch_norm_out)
804 805
    """

806 807 808 809 810 811 812 813 814 815 816
    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,
    ):
817
        super().__init__(
818 819 820 821 822 823 824 825 826
            num_features,
            momentum,
            epsilon,
            weight_attr,
            bias_attr,
            data_format,
            use_global_stats,
            name,
        )
C
ceci3 已提交
827

828 829 830
    def _check_data_format(self, input):
        if input == 'NCHW' or input == 'NC' or input == 'NCL':
            self._data_format = 'NCHW'
F
Feiyu Chan 已提交
831 832
        elif input == "NHWC" or input == 'NLC':
            self._data_format = "NHWC"
833
        else:
F
Feiyu Chan 已提交
834
            raise ValueError(
835 836
                'expected NC , NCL, NLC or None for data_format input'
            )
837

838 839
    def _check_input_dim(self, input):
        if len(input.shape) != 2 and len(input.shape) != 3:
840 841 842 843 844
            raise ValueError(
                'expected 2D or 3D input (got {}D input)'.format(
                    len(input.shape)
                )
            )
845 846


C
cnn 已提交
847
class BatchNorm2D(_BatchNormBase):
848
    r"""
849 850
    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 .

851 852
    When use_global_stats = False, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
853 854 855 856
    Calculated as follows:

    ..  math::

857 858
        \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//
        \ mini-batch\ mean \\
859
        \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i -
860
        \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\
861

862 863
    When use_global_stats = True, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are not the statistics of one mini-batch.
864 865 866 867
    They are global or running statistics (moving_mean and moving_variance). It usually got from the
    pre-trained model. Calculated as follows:

    .. math::
868 869
        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 \\
870 871 872 873 874

    The normalization function formula is as follows:

    ..  math::

875 876
        \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
877

878 879 880
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable proportional parameter
    - :math:`\beta` : trainable deviation parameter
881 882 883 884 885 886 887

    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
888
            will create ParamAttr as weight_attr. If it is set to False, the weight is not learnable.
889
            If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None.
890 891
        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
892
            will create ParamAttr as bias_attr. If it is set to False, the weight is not learnable.
893
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
F
Feiyu Chan 已提交
894
        data_format(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC". Default: NCHW.
C
ceci3 已提交
895
        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.
896 897 898
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
F
Feiyu Chan 已提交
899 900
        - 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".
901 902 903 904 905 906 907 908 909 910
        - output: 4-D tensor with same shape as input x.

    Returns:
        None

    Examples:
        .. code-block:: python

          import paddle

911
          x = paddle.rand((2, 1, 2, 3))
C
cnn 已提交
912
          batch_norm = paddle.nn.BatchNorm2D(1)
913 914
          batch_norm_out = batch_norm(x)

Z
zhang wenhui 已提交
915
          print(batch_norm_out)
916 917
    """

918
    def _check_data_format(self, input):
919
        if input == 'NCHW':
920
            self._data_format = input
F
Feiyu Chan 已提交
921 922
        elif input == "NHWC":
            self._data_format = input
923
        else:
F
Feiyu Chan 已提交
924
            raise ValueError('expected NCHW or NHWC for data_format input')
925

926 927
    def _check_input_dim(self, input):
        if len(input.shape) != 4:
928 929 930
            raise ValueError(
                'expected 4D input (got {}D input)'.format(len(input.shape))
            )
931 932


C
cnn 已提交
933
class BatchNorm3D(_BatchNormBase):
934
    r"""
935 936
    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 .

937 938
    When use_global_stats = False, the :math:`\mu_{\beta}`
    and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
939 940 941 942
    Calculated as follows:

    ..  math::

943 944 945 946
        \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 \\
947

C
ceci3 已提交
948
    When use_global_stats = True, the :math:`\\mu_{\\beta}`
949 950 951 952 953
    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::
954 955
        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 \\
956 957 958 959 960

    The normalization function formula is as follows:

    ..  math::

961 962
        \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
963

964 965 966
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable proportional parameter
    - :math:`\beta` : trainable deviation parameter
967 968 969 970 971 972 973

    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
974
            will create ParamAttr as weight_attr. If it is set to False, the weight is not learnable.
975
            If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None.
976 977
        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
978
            will create ParamAttr as bias_attr. If it is set to False, the weight is not learnable.
979
            If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None.
F
Feiyu Chan 已提交
980
        data_format(str, optional): Specify the input data format, the data format can be "NCDHW" or "NDHWC. Default: NCDHW.
C
ceci3 已提交
981
        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.
982 983 984
        name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`..

    Shape:
F
Feiyu Chan 已提交
985 986
        - 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".
987 988 989 990 991 992 993 994 995 996
        - output: 5-D tensor with same shape as input x.

    Returns:
        None

    Examples:
        .. code-block:: python

          import paddle

997
          x = paddle.rand((2, 1, 2, 2, 3))
C
cnn 已提交
998
          batch_norm = paddle.nn.BatchNorm3D(1)
999 1000
          batch_norm_out = batch_norm(x)

Z
zhang wenhui 已提交
1001
          print(batch_norm_out)
1002 1003
    """

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    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,
    ):
1015
        super().__init__(
1016 1017 1018 1019 1020 1021 1022 1023 1024
            num_features,
            momentum,
            epsilon,
            weight_attr,
            bias_attr,
            data_format,
            use_global_stats,
            name,
        )
C
ceci3 已提交
1025

1026 1027 1028
    def _check_data_format(self, input):
        if input == 'NCHW' or input == 'NCDHW':
            self._data_format = 'NCHW'
F
Feiyu Chan 已提交
1029 1030
        elif input == "NHWC" or input == "NDHWC":
            self._data_format = 'NHWC'
1031
        else:
F
Feiyu Chan 已提交
1032
            raise ValueError(
1033 1034
                'expected NCDHW, NDHWC or None for data_format input'
            )
1035

1036 1037
    def _check_input_dim(self, input):
        if len(input.shape) != 5:
1038 1039 1040
            raise ValueError(
                'expected 5D input (got {}D input)'.format(len(input.shape))
            )
1041 1042


1043
class SyncBatchNorm(_BatchNormBase):
1044
    r"""
1045

C
ceci3 已提交
1046
    This interface is used to construct a callable object of the ``SyncBatchNorm`` class.
1047 1048
    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
C
ceci3 已提交
1049 1050 1051 1052 1053 1054 1055
    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.

1056
    When model in training mode, the :math:`\\mu_{\\beta}`
C
ceci3 已提交
1057 1058 1059 1060 1061
    and :math:`\\sigma_{\\beta}^{2}` are the statistics of whole mini-batch data in all gpus.
    Calculated as follows:

    ..  math::

1062 1063 1064 1065
        \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 已提交
1066 1067 1068 1069 1070

    - :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}`
1071
    and :math:`\sigma_{\beta}^{2}` are global statistics (moving_mean and moving_variance,
C
ceci3 已提交
1072 1073 1074
    which usually got from the pre-trained model). Global statistics calculated as follows:

    .. math::
1075 1076
        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 已提交
1077 1078

    The formula of normalization is as follows:
1079

C
ceci3 已提交
1080 1081
    ..  math::

1082 1083 1084
        \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 已提交
1085

1086 1087
    - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
    - :math:`\gamma` : trainable scale parameter vector
1088
    - :math:`\beta` : trainable shift parameter vector
C
ceci3 已提交
1089

1090
    Note:
1091 1092 1093
        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.
1094

C
ceci3 已提交
1095 1096 1097 1098 1099 1100 1101
    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
1102
             is not set, the parameter is initialized with ones. If it is set to False,
C
ceci3 已提交
1103 1104 1105 1106
             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
1107
             is not set, the bias is initialized zero. If it is set to False, this layer will not
C
ceci3 已提交
1108 1109 1110
             have trainable bias parameter. Default: None.

    Shapes:
1111 1112
        - input: Tensor that the dimension from 2 to 5.
        - output: Tensor with the same shape as input.
C
ceci3 已提交
1113 1114 1115 1116

    Examples:
        .. code-block:: python

1117
            # required: gpu
1118

1119 1120
            import paddle
            import paddle.nn as nn
C
ceci3 已提交
1121

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

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
            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]]]])
1134

C
ceci3 已提交
1135 1136
    """

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    def __init__(
        self,
        num_features,
        momentum=0.9,
        epsilon=1e-05,
        weight_attr=None,
        bias_attr=None,
        data_format='NCHW',
        name=None,
    ):
1147
        super().__init__(
1148 1149 1150 1151 1152 1153 1154 1155 1156
            num_features,
            momentum,
            epsilon,
            weight_attr,
            bias_attr,
            data_format,
            None,
            name,
        )
C
ceci3 已提交
1157

C
ceci3 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    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 已提交
1168
    def forward(self, x):
C
ceci3 已提交
1169
        self._check_data_format()
C
ceci3 已提交
1170 1171 1172 1173 1174 1175
        # 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

1176 1177
        # train mode: use mini-batch stats, eval mode: use global stats
        # use_global_stats only support False in sync_batch_norm
1178
        if in_dygraph_mode():
1179
            sync_batch_norm_out, _, _, _, _, _ = _C_ops.sync_batch_norm_(
1180 1181 1182
                x,
                self._mean,
                self._variance,
1183 1184 1185
                self.weight,
                self.bias,
                not self.training,
1186 1187 1188 1189 1190 1191
                self._momentum,
                self._epsilon,
                self._data_format,
                False,
                False,
            )
1192 1193 1194
            return sync_batch_norm_out

        elif in_dynamic_mode():
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
            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,
            )
1213
            sync_batch_norm_out, _, _, _, _, _ = _legacy_C_ops.sync_batch_norm(
1214 1215 1216 1217 1218 1219 1220 1221 1222
                x,
                self.weight,
                self.bias,
                self._mean,
                self._variance,
                mean_out,
                variance_out,
                *attrs
            )
C
ceci3 已提交
1223 1224
            return sync_batch_norm_out

1225 1226 1227
        check_variable_and_dtype(
            x, 'input', ['float16', 'float32', 'float64'], 'SyncBatchNorm'
        )
C
ceci3 已提交
1228 1229 1230 1231 1232

        attrs = {
            "momentum": self._momentum,
            "epsilon": self._epsilon,
            "is_test": not self.training,
1233
            "data_layout": self._data_format,
C
ceci3 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
            "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],
1245
            "Variance": [self._variance],
C
ceci3 已提交
1246 1247 1248
        }

        saved_mean = self._helper.create_variable_for_type_inference(
1249 1250
            dtype=self._dtype, stop_gradient=True
        )
C
ceci3 已提交
1251
        saved_variance = self._helper.create_variable_for_type_inference(
1252 1253
            dtype=self._dtype, stop_gradient=True
        )
C
ceci3 已提交
1254
        sync_batch_norm_out = self._helper.create_variable_for_type_inference(
1255 1256
            self._dtype
        )
C
ceci3 已提交
1257 1258 1259 1260 1261 1262

        outputs = {
            "Y": [sync_batch_norm_out],
            "MeanOut": [mean_out],
            "VarianceOut": [variance_out],
            "SavedMean": [saved_mean],
1263
            "SavedVariance": [saved_variance],
C
ceci3 已提交
1264 1265
        }

1266 1267 1268
        self._helper.append_op(
            type="sync_batch_norm", inputs=inputs, outputs=outputs, attrs=attrs
        )
C
ceci3 已提交
1269
        return sync_batch_norm_out
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

    @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
1284

1285 1286 1287
                import paddle
                import paddle.nn as nn

C
cnn 已提交
1288
                model = nn.Sequential(nn.Conv2D(3, 5, 3), nn.BatchNorm2D(5))
1289 1290 1291 1292 1293
                sync_model = nn.SyncBatchNorm.convert_sync_batchnorm(model)

        """
        layer_output = layer
        if isinstance(layer, _BatchNormBase):
1294
            if (
1295
                layer._weight_attr is not None
1296
                and not isinstance(layer._weight_attr, bool)
1297
                and layer._weight_attr.name is not None
1298
            ):
C
ceci3 已提交
1299
                layer._weight_attr.name = layer._weight_attr.name + '_sync'
1300
            if (
1301
                layer._bias_attr is not None
1302
                and not isinstance(layer._bias_attr, bool)
1303
                and layer._bias_attr.name is not None
1304
            ):
C
ceci3 已提交
1305 1306
                layer._bias_attr.name = layer._bias_attr.name + '_sync'

1307 1308 1309 1310 1311 1312 1313 1314 1315
            layer_output = SyncBatchNorm(
                layer._num_features,
                layer._momentum,
                layer._epsilon,
                layer._weight_attr,
                layer._bias_attr,
                layer._data_format,
                layer._name,
            )
1316

1317 1318 1319 1320
            if (
                layer._weight_attr is not False
                and layer._bias_attr is not False
            ):
1321 1322 1323 1324 1325 1326
                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 已提交
1327
        for name, sublayer in layer.named_children():
1328 1329 1330
            layer_output.add_sublayer(
                name, cls.convert_sync_batchnorm(sublayer)
            )
1331 1332
        del layer
        return layer_output
1333 1334


Z
zhiboniu 已提交
1335
class LocalResponseNorm(Layer):
1336
    """
1337 1338
    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>`_
1339

1340
    See more details in :ref:`api_paddle_nn_functional_local_response_norm` .
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    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`.
1357

1358 1359 1360
    Shape:
        - input: 3-D/4-D/5-D tensor.
        - output: 3-D/4-D/5-D tensor, the same shape as input.
1361

1362
    Examples:
1363

1364
    .. code-block:: python
1365

1366 1367 1368 1369 1370 1371 1372
        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]
    """
1373

1374 1375 1376 1377 1378 1379 1380 1381 1382
    def __init__(
        self,
        size,
        alpha=0.0001,
        beta=0.75,
        k=1.0,
        data_format="NCHW",
        name=None,
    ):
1383
        super().__init__()
1384 1385 1386 1387 1388 1389 1390 1391
        self.size = size
        self.alpha = alpha
        self.beta = beta
        self.k = k
        self.data_format = data_format
        self.name = name

    def forward(self, input):
1392 1393 1394 1395 1396 1397 1398 1399 1400
        out = F.local_response_norm(
            input,
            self.size,
            self.alpha,
            self.beta,
            self.k,
            self.data_format,
            self.name,
        )
1401
        return out
1402 1403 1404

    def extra_repr(self):
        main_str = 'size={}, alpha={}, beta={}, k={}'.format(
1405 1406
            self.size, self.alpha, self.beta, self.k
        )
1407
        if self.data_format != 'NCHW':
1408 1409 1410 1411
            main_str += ', data_format={}'.format(self.data_format)
        if self.name is not None:
            main_str += ', name={}'.format(self.name)
        return main_str