-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
norm.py
1885 lines (1564 loc) · 71.9 KB
/
norm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
#
# 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.
# TODO: define normalization api
import numbers
import warnings
import numpy as np
from paddle import _C_ops, in_dynamic_mode
from paddle.device import get_all_custom_device_type
from ...fluid import dygraph_utils
from ...fluid.data_feeder import check_variable_and_dtype
from ...framework import ParamAttr, _global_flags, get_default_dtype, no_grad
from .. import functional as F
from ..functional import batch_norm, instance_norm, layer_norm
from ..initializer import Constant, Normal
from .layers import Layer
__all__ = []
class _InstanceNormBase(Layer):
"""
This class is based class for InstanceNorm1D, 2d, 3d.
See InstaceNorm1D, InstanceNorm2D or InstanceNorm3D for more details.
"""
def __init__(
self,
num_features,
epsilon=1e-5,
momentum=0.9,
weight_attr=None,
bias_attr=None,
data_format="NCHW",
name=None,
):
super().__init__()
if weight_attr is False or bias_attr is False:
assert (
weight_attr == bias_attr
), "weight_attr and bias_attr must be set to False at the same time in InstanceNorm"
self._momentum = momentum
self._epsilon = epsilon
self._weight_attr = weight_attr
self._bias_attr = bias_attr
self._num_features = num_features
self._data_format = data_format
if weight_attr is not False and bias_attr is not False:
self.scale = self.create_parameter(
attr=self._weight_attr,
shape=[num_features],
default_initializer=Constant(1.0),
is_bias=False,
)
self.bias = self.create_parameter(
attr=self._bias_attr,
shape=[num_features],
default_initializer=Constant(0.0),
is_bias=True,
)
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)
return instance_norm(
input,
weight=self.scale,
bias=self.bias,
momentum=self._momentum,
eps=self._epsilon,
data_format=self._data_format,
)
def extra_repr(self):
return 'num_features={}, epsilon={}'.format(
self._num_features, self._epsilon
)
class InstanceNorm1D(_InstanceNormBase):
r"""
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 .
DataLayout: NCL `[batch, in_channels, length]`
:math:`input` is the input features over a mini-batch.
.. math::
\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
Where `H` means height of feature map, `W` means width of feature map.
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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
data_format(str, optional): Specify the input data format, may be "NC", "NCL". Default "NCL".
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
x = paddle.rand((2, 2, 3))
instance_norm = paddle.nn.InstanceNorm1D(2)
instance_norm_out = instance_norm(x)
print(instance_norm_out)
"""
def __init__(
self,
num_features,
epsilon=0.00001,
momentum=0.9,
weight_attr=None,
bias_attr=None,
data_format="NCL",
name=None,
):
super().__init__(
num_features,
epsilon,
momentum,
weight_attr,
bias_attr,
data_format,
name,
)
def _check_input_dim(self, input):
if len(input.shape) != 2 and len(input.shape) != 3:
raise ValueError(
'expected 2D or 3D input (got {}D input)'.format(
len(input.shape)
)
)
class InstanceNorm2D(_InstanceNormBase):
r"""
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 .
DataLayout: NCHW `[batch, in_channels, in_height, in_width]`
:math:`input` is the input features over a mini-batch.
.. math::
\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
Where `H` means height of feature map, `W` means width of feature map.
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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
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
x = paddle.rand((2, 2, 2, 3))
instance_norm = paddle.nn.InstanceNorm2D(2)
instance_norm_out = instance_norm(x)
print(instance_norm_out)
"""
def __init__(
self,
num_features,
epsilon=0.00001,
momentum=0.9,
weight_attr=None,
bias_attr=None,
data_format="NCHW",
name=None,
):
super().__init__(
num_features,
epsilon,
momentum,
weight_attr,
bias_attr,
data_format,
name,
)
def _check_input_dim(self, input):
if len(input.shape) != 4:
raise ValueError(
f'expected 4D input (got {len(input.shape)}D input)'
)
class InstanceNorm3D(_InstanceNormBase):
r"""
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 .
DataLayout: NCDHW `[batch, in_channels, D, in_height, in_width]`
:math:`input` is the input features over a mini-batch.
.. math::
\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
Where `H` means height of feature map, `W` means width of feature map.
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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
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
x = paddle.rand((2, 2, 2, 2, 3))
instance_norm = paddle.nn.InstanceNorm3D(2)
instance_norm_out = instance_norm(x)
print(instance_norm_out.numpy)
"""
def __init__(
self,
num_features,
epsilon=0.00001,
momentum=0.9,
weight_attr=None,
bias_attr=None,
data_format="NCDHW",
name=None,
):
super().__init__(
num_features,
epsilon,
momentum,
weight_attr,
bias_attr,
data_format,
name,
)
def _check_input_dim(self, input):
if len(input.shape) != 5:
raise ValueError(
f'expected 5D input (got {len(input.shape)}D input)'
)
class GroupNorm(Layer):
"""
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.
num_channels(int): The number of channels of input.
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:
- x: Tensor with shape: attr:`(batch, num_features, *)`.
- output: The same shape as input x.
Returns:
None
Examples:
.. code-block:: python
import paddle
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)
print(group_norm_out)
"""
def __init__(
self,
num_groups,
num_channels,
epsilon=1e-05,
weight_attr=None,
bias_attr=None,
data_format='NCHW',
name=None,
):
super().__init__()
self._weight_attr = weight_attr
self._bias_attr = bias_attr
self._epsilon = epsilon
self._num_channels = num_channels
self._num_groups = num_groups
if data_format not in ['NCHW', 'NHWC']:
raise ValueError("unsupported data layout:" + data_format)
self._data_format = data_format
param_shape = [self._num_channels]
if weight_attr is False:
self.weight = self.create_parameter(
attr=None, shape=param_shape, default_initializer=Constant(1.0)
)
self.weight.stop_gradient = True
else:
self.weight = self.create_parameter(
attr=self._weight_attr,
shape=param_shape,
default_initializer=Constant(1.0),
)
self.weight.stop_gradient = self._weight_attr is not None and (
hasattr(self._weight_attr, "learning_rate")
and self._weight_attr.learning_rate == 0.0
)
if bias_attr is False:
self.bias = self.create_parameter(
attr=None,
shape=param_shape,
default_initializer=Constant(0.0),
is_bias=True,
)
self.bias.stop_gradient = True
else:
self.bias = self.create_parameter(
attr=self._bias_attr, shape=param_shape, is_bias=True
)
self.bias.stop_gradient = self._bias_attr is not None and (
hasattr(self._bias_attr, "learning_rate")
and self._bias_attr.learning_rate == 0.0
)
def forward(self, input):
if in_dynamic_mode():
return _C_ops.group_norm(
input,
self.weight,
self.bias,
self._epsilon,
self._num_groups,
self._data_format,
)
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
)
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(
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},
)
return self._helper.append_activation(group_norm_out, None)
def extra_repr(self):
return 'num_groups={}, num_channels={}, epsilon={}'.format(
self._num_groups, self._num_channels, self._epsilon
)
class LayerNorm(Layer):
r"""
Construct a callable object of the ``LayerNorm`` class.
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::
\mu & = \frac{1}{H}\sum_{i=1}^{H} x_i
\sigma & = \sqrt{\frac{1}{H}\sum_{i=1}^{H}{(x_i - \mu)^2} + \epsilon}
y & = f(\frac{g}{\sigma}(x - \mu) + b)
- :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
- :math:`\epsilon`: the small value added to the variance to prevent division by zero.
- :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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
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. For more information, please refer to :ref:`api_paddle_ParamAttr` .
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
x = paddle.rand((2, 2, 2, 3))
layer_norm = paddle.nn.LayerNorm(x.shape[1:])
layer_norm_out = layer_norm(x)
print(layer_norm_out)
"""
def __init__(
self,
normalized_shape,
epsilon=1e-05,
weight_attr=None,
bias_attr=None,
name=None,
):
super().__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,
default_initializer=Constant(1.0),
)
if bias_attr is False:
self.bias = None
else:
self.bias = self.create_parameter(
attr=self._bias_attr, shape=param_shape, is_bias=True
)
def forward(self, input):
return layer_norm(
input,
normalized_shape=self._normalized_shape,
weight=self.weight,
bias=self.bias,
epsilon=self._epsilon,
)
def extra_repr(self):
return 'normalized_shape={}, epsilon={}'.format(
self._normalized_shape, self._epsilon
)
class _BatchNormBase(Layer):
"""
BatchNorm base .
"""
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,
):
super().__init__()
self._num_features = num_features
self._weight_attr = weight_attr
self._bias_attr = bias_attr
self._use_global_stats = use_global_stats
if get_default_dtype() == 'float16':
self._dtype = 'float32'
else:
self._dtype = get_default_dtype()
param_shape = [num_features]
# create parameter
if weight_attr is False:
self.weight = self.create_parameter(
attr=None,
shape=param_shape,
dtype=self._dtype,
default_initializer=Constant(1.0),
)
self.weight.stop_gradient = True
else:
self.weight = self.create_parameter(
attr=self._weight_attr,
shape=param_shape,
dtype=self._dtype,
default_initializer=Constant(1.0),
)
self.weight.stop_gradient = (
self._weight_attr is not None
and self._weight_attr.learning_rate == 0.0
)
if bias_attr is False:
self.bias = self.create_parameter(
attr=None,
shape=param_shape,
dtype=self._dtype,
default_initializer=Constant(0.0),
is_bias=True,
)
self.bias.stop_gradient = True
else:
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 is not None
and self._bias_attr.learning_rate == 0.0
)
moving_mean_name = None
moving_variance_name = None
if name is not None:
moving_mean_name = name + "_mean"
moving_variance_name = name + "_variance"
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,
)
self._mean.stop_gradient = True
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,
)
self._variance.stop_gradient = True
# TODO(qili93): temporary for ascned npu performance to be removed along with npu_identity op
if (
_global_flags()['FLAGS_npu_storage_format']
and 'npu' in get_all_custom_device_type()
):
with no_grad():
weight_trans = _C_ops.npu_identity(
self.weight, 3
) # ACL_FORMAT_NC1HWC0 = 3
bias_trans = _C_ops.npu_identity(
self.bias, 3
) # ACL_FORMAT_NC1HWC0 = 3
mean_trans = _C_ops.npu_identity(
self._mean, 3
) # ACL_FORMAT_NC1HWC0 = 3
var_trans = _C_ops.npu_identity(
self._variance, 3
) # ACL_FORMAT_NC1HWC0 = 3
weight_trans._share_underline_tensor_to(self.weight)
bias_trans._share_underline_tensor_to(self.bias)
mean_trans._share_underline_tensor_to(self._mean)
var_trans._share_underline_tensor_to(self._variance)
self._data_format = data_format
self._in_place = False
self._momentum = momentum
self._epsilon = epsilon
self._fuse_with_relu = False
self._name = name
def _check_input_dim(self, input):
raise NotImplementedError("BatchNorm Base error")
def _check_data_format(self, input):
raise NotImplementedError("BatchNorm Base data format error")
def forward(self, input):
self._check_data_format(self._data_format)
self._check_input_dim(input)
if self.training:
warnings.warn(
"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,
)
def extra_repr(self):
main_str = 'num_features={}, momentum={}, epsilon={}'.format(
self._num_features, self._momentum, self._epsilon
)
if self._data_format != 'NCHW':
main_str += f', data_format={self._data_format}'
if self._name is not None:
main_str += f', name={self._name}'
return main_str
class BatchNorm(Layer):
r"""
This interface is used to construct a callable object of the ``BatchNorm`` class.
For more details, refer to code examples.
It implements the function of the Batch Normalization Layer and can be used
as a normalizer function for conv2d and fully connected operations.
The data is normalized by the mean and variance of the channel based on the current batch data.
Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing
Internal Covariate Shift <https://arxiv.org/pdf/1502.03167.pdf>`_
for more details.
When use_global_stats = False, the :math:`\mu_{\beta}`
and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch.
Calculated as follows:
.. math::
\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 \\
- :math:`x` : mini-batch data
- :math:`m` : the size of the mini-batch data
When use_global_stats = True, the :math:`\\mu_{\\beta}`
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::
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 \\
The normalization function formula is as follows:
.. math::
\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
- :math:`\epsilon` : add a smaller value to the variance to prevent division by zero
- :math:`\gamma` : trainable proportional parameter
- :math:`\beta` : trainable deviation parameter
Parameters:
num_channels(int): Indicate the number of channels of the input ``Tensor``.
act(str, optional): Activation to be applied to the output of batch normalization. Default: None.
is_test (bool, optional): A flag indicating whether it is in test phrase or not.
This flag only has effect on static graph mode. For dygraph mode, please use ``eval()``.
Default: False.
momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9.
epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5.
param_attr(ParamAttr, 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 param_attr. If the Initializer of the param_attr
is not set, the parameter is initialized with Xavier. Default: None.
bias_attr(ParamAttr, 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 the Initializer of the bias_attr
is not set, the bias is initialized zero. Default: None.
dtype(str, optional): Indicate the data type of the input ``Tensor``,
which can be float32 or float64. Default: float32.
data_layout(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC", where `N` is batch size, `C` is the number of the feature map, `H` is the height of the feature map, `W` is the width of the feature map. Default: NCHW.
in_place(bool, optional): Make the input and output of batch norm reuse memory. Default: False.
moving_mean_name(str, optional): The name of moving_mean which store the global Mean. Default: None.
moving_variance_name(str, optional): The name of the moving_variance which store the global Variance. Default: None.
do_model_average_for_mean_and_var(bool, optional): Whether parameter mean and variance should do model
average when model average is enabled. Default: True.
use_global_stats(bool, optional): Whether to use global mean and
variance. In inference or test mode, set use_global_stats to true
or is_test to true, and the behavior is equivalent.
In train mode, when setting use_global_stats True, the global mean
and variance are also used during train period. Default: False.
trainable_statistics(bool, optional): Whether to calculate mean and var in eval mode. In eval mode, when
setting trainable_statistics True, mean and variance will be calculated by current batch statistics.
Default: False.
Returns:
None
Examples:
.. code-block:: python
import paddle.fluid as fluid
import paddle.nn as nn
from paddle.fluid.dygraph.base import to_variable
import numpy as np
x = np.random.random(size=(3, 10, 3, 7)).astype('float32')
with fluid.dygraph.guard():
x = to_variable(x)
batch_norm = nn.layer.norm.BatchNorm(10)
hidden1 = batch_norm(x)
"""
def __init__(
self,
num_channels,
act=None,
is_test=False,
momentum=0.9,
epsilon=1e-05,
param_attr=None,
bias_attr=None,
dtype='float32',
data_layout='NCHW',
in_place=False,
moving_mean_name=None,
moving_variance_name=None,
do_model_average_for_mean_and_var=True,
use_global_stats=False,
trainable_statistics=False,
):
super().__init__()
self._param_attr = param_attr
self._bias_attr = bias_attr
self._act = act
self._use_mkldnn = _global_flags()["FLAGS_use_mkldnn"]
assert (
bias_attr is not False
), "bias_attr should not be False in batch_norm."
if dtype == "float16":
self._dtype = "float32"
else:
self._dtype = dtype
param_shape = [num_channels]
# create parameter
self.weight = self.create_parameter(
attr=self._param_attr,
shape=param_shape,
dtype=self._dtype,
default_initializer=Constant(1.0),
)
self.weight.stop_gradient = (
use_global_stats and self._param_attr.learning_rate == 0.0
)
self.bias = self.create_parameter(
attr=self._bias_attr,
shape=param_shape,
dtype=self._dtype,
is_bias=True,
)
self.bias.stop_gradient = (
use_global_stats and self._param_attr.learning_rate == 0.0
)
self._mean = self.create_parameter(
attr=ParamAttr(
name=moving_mean_name,
initializer=Constant(0.0),
trainable=False,
do_model_average=do_model_average_for_mean_and_var,
),
shape=param_shape,
dtype=self._dtype,
)
self._mean.stop_gradient = True
self._variance = self.create_parameter(
attr=ParamAttr(
name=moving_variance_name,
initializer=Constant(1.0),
trainable=False,
do_model_average=do_model_average_for_mean_and_var,
),
shape=param_shape,
dtype=self._dtype,
)
self._variance.stop_gradient = True
# TODO(qili93): temporary for ascned npu performance to be removed along with npu_identity op
if (
_global_flags()['FLAGS_npu_storage_format']
and 'npu' in get_all_custom_device_type()
):
if in_dynamic_mode():
with no_grad():
weight_trans = _C_ops.npu_identity(
self.weight, 3
) # ACL_FORMAT_NC1HWC0 = 3
bias_trans = _C_ops.npu_identity(
self.bias, 3
) # ACL_FORMAT_NC1HWC0 = 3
mean_trans = _C_ops.npu_identity(
self._mean, 3
) # ACL_FORMAT_NC1HWC0 = 3
var_trans = _C_ops.npu_identity(