-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
common.py
4263 lines (3653 loc) · 172 KB
/
common.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) 2022 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.
import inspect
import warnings
from functools import reduce
import numpy as np
import paddle
from paddle.base import core, unique_name
from paddle.base.data_feeder import check_dtype
from paddle.base.framework import (
Program,
Variable,
default_main_program,
in_dygraph_mode,
in_dynamic_or_pir_mode,
in_pir_mode,
name_scope,
program_guard,
static_only,
)
from paddle.base.layers.layer_function_generator import templatedoc
from paddle.base.param_attr import ParamAttr
from paddle.base.wrapped_decorator import signature_safe_contextmanager
from paddle.common_ops_import import (
LayerHelper,
check_type,
check_variable_and_dtype,
)
from paddle.nn.initializer import Constant, Normal
__all__ = []
@static_only
def fc(
x,
size,
num_flatten_dims=1,
weight_attr=None,
bias_attr=None,
activation=None,
name=None,
):
r"""
Fully-Connected layer can take a tensor or a list of tensor as its inputs.
It creates a 2-D weight tensor for each input tensor, which represents its
weight matrix from each input unit to each output unit. The fully connected
layer multiplies each input tensor with its corresponding weight to produce
an output tensor with shape :math:`[batch\_size, *, size]` , where :math:`*`
means any number of additional dimensions. If a list of tensor is given,
the results of multiple output tensors with shape :math:`[batch\_size, *, size]`
will be summed up. If :attr:`bias_attr` is not False, a 1-D bias tensor will
be created and added to the output. Finally, if :attr:`activation` is not None,
it will be applied to the output as well.
For a single input tensor :math:`X` , the equation is:
.. math::
Out = Act({XW + b})
For a list of input tensor, the equation is:
.. math::
Out = Act({\sum_{i=0}^{N-1}X_iW_i + b})
where:
* :math:`N`: The number of the input tensors. :math:`N` equals to :math:`len(X)` if :math:`X` is list of tensor.
* :math:`X_i`: The i-th input tensor.
* :math:`W_i`: The i-th weight matrix corresponding i-th input tensor.
* :math:`b`: The bias created by this layer (if needed).
* :math:`Act`: The activation function.
* :math:`Out`: The output tensor.
.. code-block:: text
# Case 1, input is a single tensor:
x.data = [[[0.1, 0.2],
[0.3, 0.4]]]
x.shape = (1, 2, 2) # 1 is batch_size
out = paddle.static.nn.fc(x=x, size=1, num_flatten_dims=2)
# Get the output:
out.data = [[0.83234344], [0.34936576]]
out.shape = (1, 2, 1)
# Case 2, input is a list of tensor:
x0.data = [[[0.1, 0.2],
[0.3, 0.4]]]
x0.shape = (1, 2, 2) # 1 is batch_size
x1.data = [[[0.1, 0.2, 0.3]]]
x1.shape = (1, 1, 3)
out = paddle.static.nn.fc(x=[x0, x1], size=2)
# Get the output:
out.data = [[0.18669507, 0.1893476]]
out.shape = (1, 2)
Args:
x (Tensor|list[Tensor]|tuple[Tensor]): A tensor or a list/tuple of tensors. The number of dimensions
of each tensor is at least 2. The data type should be float16, float32 or float64.
size (int): The number of output units in this layer, which also means the feature
size of output tensor.
num_flatten_dims (int, optional): The fc layer can accept an input tensor with more than
two dimensions. If this happens, the multi-dimensional tensor will first be flattened
into a 2-D matrix. The parameter :attr:`num_flatten_dims` determines how the input
tensor is flattened: the first :math:`num\_flatten\_dims` (inclusive, index starts from 1)
dimensions will be flatten to form the first dimension of the final matrix (height of
the matrix), and the rest :math:`rank(x) - num\_flatten\_dims` dimensions are
flattened to form the second dimension of the final matrix (width of the matrix).
For example, assuming that :attr:`x` is a 5-dimensional tensor with a shape
:math:`[2, 3, 4, 5, 6]` , and :attr:`num_flatten_dims` = 3.
Then, the flattened matrix will have a shape :math:`[2 * 3 * 4, 5 * 6] = [24, 30]` .
Default: 1.
weight_attr (ParamAttr, optional): The attribute for the learnable weight.
The default value is None, and the weight will be initialized to zero.
For detailed information, please refer to :attr:`paddle.ParamAttr`.
Warning, if x is a list of tensor, weight_attr should also be a list of same length.
bias_attr (ParamAttr|bool, optional): The attribute of the learnable bias.
If it is set to False, no bias will be added to the output.
If it is set to None or one kind of ParamAttr, a bias parameter will
be created according to ParamAttr. For detailed information, please refer
to :attr:`paddle.ParamAttr`. The default value is None and the bias will be
initialized to zero.
activation (str, optional): Activation to be applied to the output of
this layer, such as tanh, softmax, sigmoid, relu. For more information,
please refer to :ref:`api_guide_activations_en` . Default: None.
name (str, optional): The default value is None. Normally there is no need for user to set
it. For more information, please refer to :ref:`api_guide_Name` .
Returns:
Tensor, its shape is :math:`[batch\_size, *, size]` , and the data type is same with input.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> # When input is a single tensor
>>> x = paddle.static.data(name="x", shape=[1, 2, 2], dtype="float32")
>>> out = paddle.static.nn.fc(
... x=x,
... size=1,
... num_flatten_dims=2,
... weight_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=0.5)),
... bias_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0)))
>>> print(out)
var fc_0.tmp_1 : LOD_TENSOR.shape(1, 2, 1).dtype(float32).stop_gradient(False)
>>> # When input is multiple tensors
>>> x0 = paddle.static.data(name="x0", shape=[1, 2, 2], dtype="float32")
>>> x1 = paddle.static.data(name="x1", shape=[1, 1, 3], dtype="float32")
>>> out = paddle.static.nn.fc(
... x=[x0, x1],
... size=2,
... weight_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=0.5)),
... bias_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0)))
>>> print(out)
var fc_1.tmp_3 : LOD_TENSOR.shape(1, 2).dtype(float32).stop_gradient(False)
"""
def fc_base(
input,
size,
num_flatten_dims=1,
param_attr=None,
bias_attr=None,
act=None,
name=None,
):
helper = LayerHelper("fc", **locals())
check_type(
input, 'input', (list, tuple, Variable, paddle.pir.Value), 'fc'
)
if isinstance(input, (list, tuple)):
for i, input_x in enumerate(input):
check_type(
input_x,
'input[' + str(i) + ']',
(Variable, paddle.pir.Value),
'fc',
)
dtype = helper.input_dtype()
check_dtype(
dtype, 'input', ['float16', 'uint16', 'float32', 'float64'], 'fc'
)
mul_results = []
for input_var, param_attr in helper.iter_inputs_and_params():
input_shape = input_var.shape
if num_flatten_dims == -1:
num_flatten_dims = len(input_shape) - 1
param_shape = [
reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1)
] + [size]
w = helper.create_parameter(
attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False
)
if in_pir_mode():
if len(input_var.shape) > 2:
new_shape = (
input_var.shape[0],
np.prod(input_var.shape[1:]),
)
input_var = paddle.reshape(input_var, new_shape)
tmp = paddle.matmul(input_var, w)
else:
tmp = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type="mul",
inputs={"X": input_var, "Y": w},
outputs={"Out": tmp},
attrs={
"x_num_col_dims": num_flatten_dims,
"y_num_col_dims": 1,
},
)
mul_results.append(tmp)
if len(mul_results) == 1:
pre_bias = mul_results[0]
elif in_pir_mode():
pre_bias = paddle.add_n(mul_results)
else:
pre_bias = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type="sum",
inputs={"X": mul_results},
outputs={"Out": pre_bias},
attrs={},
)
# add bias
pre_activation = helper.append_bias_op(
pre_bias, dim_start=num_flatten_dims
)
# add activation
return helper.append_activation(pre_activation)
return fc_base(
input=x,
size=size,
num_flatten_dims=num_flatten_dims,
param_attr=weight_attr,
bias_attr=bias_attr,
act=activation,
name=name,
)
def instance_norm(
input, epsilon=1e-05, param_attr=None, bias_attr=None, name=None
):
r"""
**Instance Normalization Layer**
Can be used as a normalizer function for convolution or fully_connected operations.
The required data format for this layer is one of the following:
DataLayout: NCHW `[batch, in_channels, in_height, in_width]`
Refer to `Instance Normalization: The Missing Ingredient for
Fast Stylization <https://arxiv.org/pdf/1607.08022.pdf>`_
for more details.
: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
Note:
`H` means height of feature map, `W` means width of feature map.
Args:
input(Tensor): The rank of input tensor can be 2, 3, 4, 5.
The data type is float32 or float64.
epsilon(float, Default 1e-05): A value added to the denominator for
numerical stability. Default is 1e-5.
param_attr(ParamAttr|None|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 param_attr, the name of scale can be set in ParamAttr.
If the Initializer of the param_attr is not set, the parameter is initialized
with Xavier. If the param_attr is set to False, instance_norm will not create param_attr.
Default: None.
bias_attr(ParamAttr|None|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 the bias_attr is set to False, instance_norm will not create bias_attr.
Default: None.
name(string, Default None): A name for this layer(optional). If set None, the layer
will be named automatically.
Returns:
A Tensor which is the result after applying instance normalization on the input,
has same shape and data type with input.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> x = paddle.static.data(name='x', shape=[3, 7, 3, 7], dtype='float32')
>>> hidden1 = paddle.static.nn.fc(x, size=200)
>>> hidden2 = paddle.static.nn.instance_norm(hidden1)
"""
check_variable_and_dtype(
input,
'input',
['uint16', 'float16', 'float32', 'float64'],
'instance_norm',
)
if param_attr is False:
assert (
bias_attr is False
), "param_attr and bias_attr must be set to False at the same time in instance_norm"
helper = LayerHelper('instance_norm', **locals())
dtype = helper.input_dtype()
# use fp32 for in parameter
if dtype == paddle.float16:
dtype = paddle.float32
input_shape = input.shape
if len(input.shape) < 2 or len(input.shape) > 5:
raise ValueError(
f'expected 2D or 3D or 4D or 5D input (got {len(input.shape)}D input, input shape is: {input_shape})'
)
channel_num = input_shape[1]
param_shape = [channel_num]
if param_attr and bias_attr:
# create parameter
scale = helper.create_parameter(
attr=helper.param_attr,
shape=param_shape,
dtype=dtype,
default_initializer=Constant(1.0),
)
bias = helper.create_parameter(
attr=helper.bias_attr,
shape=param_shape,
dtype=dtype,
is_bias=True,
default_initializer=Constant(0.0),
)
# create output
saved_mean = helper.create_variable_for_type_inference(
dtype=dtype, stop_gradient=True
)
saved_variance = helper.create_variable_for_type_inference(
dtype=dtype, stop_gradient=True
)
instance_norm_out = helper.create_variable_for_type_inference(dtype)
inputs = {"X": input}
if param_attr and bias_attr:
inputs["Scale"] = scale
inputs["Bias"] = bias
helper.append_op(
type="instance_norm",
inputs=inputs,
outputs={
"Y": instance_norm_out,
"SavedMean": saved_mean,
"SavedVariance": saved_variance,
},
attrs={
"epsilon": epsilon,
},
)
return instance_norm_out
@static_only
def continuous_value_model(input, cvm, use_cvm=True):
r"""
**continuous_value_model layers**
Now, this OP is used in CTR project to remove or dispose show and click value in :attr:`input`.
:attr:`input` is an embedding vector including show and click value, whose shape is :math:`[N, D]` (N is batch size. D is `2 + embedding dim` ).
Show and click at first two dims of embedding vector D.
If :attr:`use_cvm` is True, it will calculate :math:`log(show)` and :math:`log(click)` , and output shape is :math:`[N, D]` .
If :attr:`use_cvm` is False, it will remove show and click from :attr:`input` , and output shape is :math:`[N, D - 2]` .
:attr:`cvm` is show_click info, whose shape is :math:`[N, 2]` .
Args:
input (Variable): The input variable. A 2-D LoDTensor with shape :math:`[N, D]` , where N is the batch size, D is `2 + the embedding dim` . `lod level = 1` .
A Tensor with type float32, float64.
cvm (Variable): Show and click variable. A 2-D Tensor with shape :math:`[N, 2]` , where N is the batch size, 2 is show and click.
A Tensor with type float32, float64.
use_cvm (bool): Use show_click or not. if use, the output dim is the same as input.
if not use, the output dim is `input dim - 2` (remove show and click)
Returns:
Variable: A 2-D LodTensor with shape :math:`[N, M]` . if :attr:`use_cvm` = True, M is equal to input dim D. if False, M is equal to `D - 2`. \
A Tensor with same type as input.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> input = paddle.static.data(name="input", shape=[64, 1], dtype="int64")
>>> label = paddle.static.data(name="label", shape=[64, 1], dtype="int64")
>>> w0 = paddle.full(shape=(100, 1), fill_value=2).astype(paddle.float32)
>>> embed = paddle.nn.functional.embedding(input, w0)
>>> ones = paddle.full_like(label, 1, dtype="int64")
>>> show_clk = paddle.cast(paddle.concat([ones, label], axis=1), dtype='float32')
>>> show_clk.stop_gradient = True
>>> input_with_cvm = paddle.static.nn.continuous_value_model(embed[:, 0], show_clk, True)
"""
helper = LayerHelper('cvm', **locals())
out = helper.create_variable(dtype=input.dtype)
check_variable_and_dtype(
input, 'input', ['float16', 'float32', 'float64'], 'cvm'
)
helper.append_op(
type='cvm',
inputs={'X': [input], 'CVM': [cvm]},
outputs={'Y': [out]},
attrs={"use_cvm": use_cvm},
)
return out
@static_only
def data_norm(
input,
act=None,
epsilon=1e-05,
param_attr=None,
data_layout='NCHW',
in_place=False,
name=None,
moving_mean_name=None,
moving_variance_name=None,
do_model_average_for_mean_and_var=True,
slot_dim=-1,
sync_stats=False,
summary_decay_rate=0.9999999,
enable_scale_and_shift=False,
):
r"""
**Data Normalization Layer**
This op can be used as a normalizer function for conv2d and fully_connected operations.
The required data format for this layer is one of the following:
1. NHWC `[batch, in_height, in_width, in_channels]`
2. NCHW `[batch, in_channels, in_height, in_width]`
:math:`input` is the input features over a mini-batch.
.. 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 \\
\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
Args:
input (Tensor): The input Tensor.
act (str, optional): Activation type, linear|relu|prelu|... Default: None.
epsilon(float, optional): Whether to add small values into the variance during calculations
to prevent division by zero. Default: 1e-05.
param_attr (ParamAttr, optional): The parameter attribute for Parameter `scale`. Default: None.
data_layout (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: `"NCHW"`, `"NHWC"`.
The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
`[batch_size, input_channels, input_height, input_width]`. Default: `"NCHW"`.
in_place (bool, optional): Make the input and output of batch norm reuse memory. Default: False.
name (str, optional): A name for this layer (optional). If set None, the layer
will be named automatically. Default: None.
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.
slot_dim (int, optional): The embedding dimension of one slot. Slot is a set of one specific feature. In pslib mode,
we distinguish feature ids by slot and pull their embeddings from parameter server (pslib). The first
place of the embedding is the historical show number (occurrence time of this feature id with a label 0).
If the input of this op is concated by slot-wise embeddings, and the show number is zero when this slot
is new or empty, the normalization result may be impractical. To avoid this, we add slot_dim to locate
the show number and judge if the show number is zero. If so, we choose to skip normalization on this
embedding. Default: -1.
sync_stats (bool, optional): When running with multiple GPU cards, using allreduce to sync the
summary messages. Default: False.
summary_decay_rate (float, optional): The decay rate when updating summary. Default: 0.9999999.
enable_scale_and_shift (bool, optional): do scale&shift after normalization. Default: False.
Returns:
Tensor: A tensor which is the result after applying data normalization on the input.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> x = paddle.randn(shape=[32, 100])
>>> hidden2 = paddle.static.nn.data_norm(input=x)
"""
helper = LayerHelper('data_norm', **locals())
dtype = helper.input_dtype()
input_shape = input.shape
if len(input_shape) < 2:
raise ValueError(
f"The shape pf Input < 2 (got {len(input_shape)}D input, input shape is: {input_shape})"
)
if data_layout == 'NCHW':
channel_num = input_shape[1]
else:
if data_layout == 'NHWC':
channel_num = input_shape[-1]
else:
raise ValueError("unsupported data layout:" + data_layout)
param_shape = [channel_num]
batch_size_default = 1e4
batch_sum_default = 0.0
batch_square_sum_default = 1e4
scale_w_default = 1.0
bias_default = 0.0
if param_attr and isinstance(param_attr, dict):
batch_size_default = param_attr.get("batch_size", 1e4)
batch_sum_default = param_attr.get("batch_sum", 0.0)
batch_square_sum_default = param_attr.get("batch_square", 1e4)
if enable_scale_and_shift:
scale_w_default = param_attr.get("scale_w", 1.0)
bias_default = param_attr.get("bias", 0.0)
# create scale and shift(bias) when enable_scale_and_shift is True
if name is None:
name = "dn"
if enable_scale_and_shift:
scale_w = helper.create_parameter(
attr=ParamAttr(
name=name + '.scale_w',
initializer=Constant(value=float(scale_w_default)),
trainable=True,
),
shape=param_shape,
dtype=input.dtype,
)
bias = helper.create_parameter(
attr=ParamAttr(
name=name + '.bias',
initializer=Constant(value=float(bias_default)),
trainable=True,
),
shape=param_shape,
dtype=input.dtype,
)
# create parameter
batch_size = helper.create_parameter(
attr=ParamAttr(
name=name + '.batch_size',
initializer=Constant(value=float(batch_size_default)),
trainable=True,
),
shape=param_shape,
dtype=input.dtype,
)
batch_sum = helper.create_parameter(
attr=ParamAttr(
name=name + '.batch_sum',
initializer=Constant(value=float(batch_sum_default)),
trainable=True,
),
shape=param_shape,
dtype=input.dtype,
)
batch_square_sum = helper.create_parameter(
attr=ParamAttr(
name=name + '.batch_square_sum',
initializer=Constant(value=float(batch_square_sum_default)),
trainable=True,
),
shape=param_shape,
dtype=input.dtype,
)
means = helper.create_variable(dtype=dtype, stop_gradient=True)
scales = helper.create_variable(dtype=dtype, stop_gradient=True)
data_norm_out = input if in_place else helper.create_variable(dtype=dtype)
inputs = {
"X": input,
"BatchSize": batch_size,
"BatchSum": batch_sum,
"BatchSquareSum": batch_square_sum,
}
attrs = {
"epsilon": epsilon,
"data_layout": data_layout,
"sync_stats": sync_stats,
"summary_decay_rate": summary_decay_rate,
}
if slot_dim > 0:
attrs["slot_dim"] = slot_dim
if enable_scale_and_shift:
attrs["enable_scale_and_shift"] = enable_scale_and_shift
if enable_scale_and_shift:
inputs["scale_w"] = scale_w
inputs["bias"] = bias
helper.append_op(
type="data_norm",
inputs=inputs,
outputs={
"Y": data_norm_out,
"Means": means,
"Scales": scales,
"BatchSize": batch_size,
"BatchSum": batch_sum,
"BatchSquareSum": batch_square_sum,
},
attrs=attrs,
)
return helper.append_activation(data_norm_out)
@templatedoc()
def group_norm(
input,
groups,
epsilon=1e-05,
param_attr=None,
bias_attr=None,
act=None,
data_layout='NCHW',
name=None,
):
"""
**Group Normalization Layer**
Refer to `Group Normalization <https://arxiv.org/abs/1803.08494>`_ .
Parameters:
input(Tensor): Tensor with dimension greater than 1, the data type is float32 or float64.
groups(int): The number of groups that divided from channels, the data type
is int32.
epsilon(float, optional): The small value added to the variance to prevent
division by zero, the data type is float32. Default: 1e-05.
param_attr(ParamAttr|bool, optional): ParamAttr object that specifies weight parameter
attribute. If a bool type, only False is supported, which means there is no weight parameter.
Default: None, the default weight parameter attribute is used. For more information, please
refer to :ref:`api_guide_ParamAttr` .
bias_attr(ParamAttr|bool, optional): ParamAttr object that specifies bias parameter
attribute. If a bool type, only False is supported, which means there is no bias parameter.
Default: None, the default bias parameter attribute is used. For more information, please
refer to :ref:`api_guide_ParamAttr` .
act(str, optional): Activation to be applied to the output of group normalization.
data_layout(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: `"NCHW"`, `"NHWC"`.
The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
`[batch_size, input_channels, *]`.
name (str, optional): The default value is None. Normally there is no need for user to set this
property. For more information, please refer to :ref:`api_guide_Name` .
Returns:
Tensor: A Tensor has same data type and data format with `input`.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> data = paddle.static.data(name='data', shape=[2, 8, 32, 32], dtype='float32')
>>> x = paddle.static.nn.group_norm(input=data, groups=4)
>>> print(x.shape)
(2, 8, 32, 32)
"""
helper = LayerHelper('group_norm', **locals())
dtype = helper.input_dtype()
check_variable_and_dtype(
input,
'input',
['float16', 'uint16', 'float32', 'float64'],
'group_norm',
)
# create input and parameters
inputs = {'X': input}
input_shape = input.shape
if len(input_shape) < 2:
raise ValueError(
f"The dimensions of Op(static.nn.group_norm)'s input should be more than 1. But received {len(input_shape)}"
)
if data_layout != 'NCHW' and data_layout != 'NHWC':
raise ValueError(
"Param(data_layout) of Op(static.nn.group_norm) got wrong value: received "
+ data_layout
+ " but only NCHW or NHWC supported."
)
channel_num = input_shape[1] if data_layout == 'NCHW' else input_shape[-1]
param_shape = [channel_num]
if param_attr:
scale = helper.create_parameter(
attr=helper.param_attr,
shape=param_shape,
dtype=dtype,
default_initializer=Constant(1.0),
)
inputs['Scale'] = scale
if bias_attr:
bias = helper.create_parameter(
attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True
)
inputs['Bias'] = bias
# create output
mean_out = helper.create_variable(dtype=dtype, stop_gradient=True)
variance_out = helper.create_variable(dtype=dtype, stop_gradient=True)
group_norm_out = helper.create_variable(dtype=dtype)
helper.append_op(
type="group_norm",
inputs=inputs,
outputs={
"Y": group_norm_out,
"Mean": mean_out,
"Variance": variance_out,
},
attrs={
"epsilon": epsilon,
"groups": groups,
"data_layout": data_layout,
},
)
return helper.append_activation(group_norm_out)
def conv2d(
input,
num_filters,
filter_size,
stride=1,
padding=0,
dilation=1,
groups=None,
param_attr=None,
bias_attr=None,
use_cudnn=True,
act=None,
name=None,
data_format="NCHW",
):
r"""
The convolution2D layer calculates the output based on the input, filter
and strides, paddings, dilations, groups parameters. Input and
Output are in NCHW or NHWC format, where N is batch size, C is the number of
channels, H is the height of the feature, and W is the width of the feature.
Filter is in MCHW format, where M is the number of output image channels,
C is the number of input image channels, H is the height of the filter,
and W is the width of the filter. If the groups is greater than 1,
C will equal the number of input image channels divided by the groups.
Please refer to UFLDL's `convolution
<http://ufldl.stanford.edu/tutorial/supervised/FeatureExtractionUsingConvolution/>`_
for more details.
If bias attribution and activation type are provided, bias is added to the
output of the convolution, and the corresponding activation function is
applied to the final result.
For each input :math:`X`, the equation is:
.. math::
Out = \sigma (W \\ast X + b)
Where:
* :math:`X`: Input value, a tensor with NCHW or NHWC format.
* :math:`W`: Filter value, a tensor with MCHW format.
* :math:`\\ast`: Convolution operation.
* :math:`b`: Bias value, a 2-D tensor with shape [M, 1].
* :math:`\\sigma`: Activation function.
* :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
Example:
- Input:
Input shape: :math:`(N, C_{in}, H_{in}, W_{in})`
Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)`
- Output:
Output shape: :math:`(N, C_{out}, H_{out}, W_{out})`
Where
.. math::
H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\
W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1
Args:
input (Tensor): The input is 4-D Tensor with shape [N, C, H, W], the data type
of input is float16 or float32 or float64.
num_filters(int): The number of filter. It is as same as the output
image channel.
filter_size (int|tuple): The filter size. If filter_size
is a tuple, it must contain two integers, (filter_size_height,
filter_size_width). Otherwise, filter_size_height = filter_size_width =\
filter_size.
stride (int|tuple, optional): The stride size. It means the stride in convolution.
If stride is a tuple, it must contain two integers, (stride_height, stride_width).
Otherwise, stride_height = stride_width = stride. Default: stride = 1.
padding (string|int|list|tuple, optional): The padding size. It means the number of zero-paddings
on both sides for each dimension.If `padding` is a string, either 'VALID' or
'SAME' which is the padding algorithm. If padding size is a tuple or list,
it could be in three forms: `[pad_height, pad_width]` or
`[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when
`data_format` is `"NCHW"`, `padding` can be in the form `[[0,0], [0,0],
[pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`.
when `data_format` is `"NHWC"`, `pool_padding` can be in the form
`[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`.
Default: padding = 0.
dilation (int|tuple, optional): The dilation size. It means the spacing between the kernel
points. If dilation is a tuple, it must contain two integers, (dilation_height,
dilation_width). Otherwise, dilation_height = dilation_width = dilation.
Default: dilation = 1.
groups (int, optional): The groups number of the Conv2d Layer. According to grouped
convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
the first half of the filters is only connected to the first half
of the input channels, while the second half of the filters is only
connected to the second half of the input channels. Default: groups=1.
param_attr (ParamAttr|None, optional): The parameter attribute for learnable parameters/weights
of conv2d. If it is set to None or one attribute of ParamAttr, conv2d
will create ParamAttr as param_attr. If the Initializer of the param_attr
is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
and the :math:`std` is :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
bias_attr (ParamAttr|bool|None, optional): The parameter attribute for the bias of conv2d.
If it is set to False, no bias will be added to the output units.
If it is set to None or one attribute of ParamAttr, conv2d
will create ParamAttr as bias_attr. If the Initializer of the bias_attr
is not set, the bias is initialized zero. Default: None.
use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn
library is installed. Default: True
act (str, optional): Activation type, if it is set to None, activation is not appended.
Default: None
name(str|None, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
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: `"NCHW"`, `"NHWC"`.
The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
`[batch_size, input_channels, input_height, input_width]`.
Returns:
A Tensor representing the conv2d, whose data type is the
same with input. If act is None, the tensor storing the convolution
result, and if act is not None, the tensor storing convolution
and non-linearity activation result.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.enable_static()
>>> data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32')
>>> conv2d = paddle.static.nn.conv2d(input=data, num_filters=2, filter_size=3, act="relu")
>>> print(conv2d.shape)
(-1, 2, 30, 30)
"""
check_variable_and_dtype(
input, 'input', ['uint16', 'float16', 'float32', 'float64'], 'conv2d'
)
if len(input.shape) != 4:
raise ValueError(
"Input size should be 4, " f"but received {len(input.shape)}"
)
num_channels = input.shape[1]
if not isinstance(use_cudnn, bool):
raise ValueError(
"Attr(use_cudnn) should be True or False. Received "
"Attr(use_cudnn): %s. " % str(use_cudnn)
)
if data_format not in ["NCHW", "NHWC"]:
raise ValueError(
"Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
"Attr(data_format): %s." % str(data_format)
)
channel_last = data_format == "NHWC"
num_channels = input.shape[3] if channel_last else input.shape[1]
if num_channels < 0:
raise ValueError(
f"The channel dimension of the input({str(input.shape)}) should be defined. "
f"Received: {str(num_channels)}."
)
assert param_attr is not False, "param_attr should not be False here."
if groups is None:
num_filter_channels = num_channels
elif groups <= 0:
raise ValueError(
"the groups of input must be greater than 0, "
f"but received the groups of input is {groups}"
)
else:
if num_channels % groups != 0:
raise ValueError(
"the channel of input must be divisible by groups,"
f"received: the channel of input is {num_channels}, the shape of input is {input.shape}"
f", the groups is {groups}"
)
num_filter_channels = num_channels // groups
l_type = 'conv2d'
if (
num_channels == groups
and num_filters % num_channels == 0
and not use_cudnn
):
l_type = 'depthwise_conv2d'
if (
num_channels == groups
and num_filters % num_channels == 0
and core.is_compiled_with_rocm()
):
l_type = 'depthwise_conv2d'
helper = LayerHelper(l_type, **locals())
dtype = helper.input_dtype()
filter_size = paddle.utils.convert_to_list(filter_size, 2, 'filter_size')
stride = paddle.utils.convert_to_list(stride, 2, 'stride')
dilation = paddle.utils.convert_to_list(dilation, 2, 'dilation')
# padding
def _update_padding(padding, data_format):
if isinstance(padding, (list, tuple)) and len(padding) == 4:
if isinstance(padding[0], (list, tuple)) and (
data_format == "NCHW"
):
if not (padding[0] == [0, 0] and padding[1] == [0, 0]):
raise ValueError(
"Non-zero padding(%s) in the batch or channel dimensions "
"is not supported." % str(padding)
)
padding = padding[2:4]
padding = [ele for a_list in padding for ele in a_list]
elif isinstance(padding[0], (list, tuple)) and (
data_format == "NHWC"
):
if not (padding[0] == [0, 0] and padding[3] == [0, 0]):