-
Notifications
You must be signed in to change notification settings - Fork 2
/
wnnlayer.py
executable file
·2021 lines (1810 loc) · 84.5 KB
/
wnnlayer.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
import tensorflow as tf
import tfop
import wml_tfutils as wmlt
from tensorflow.python.training import moving_averages
from tensorflow.python.ops import variable_scope
from tensorflow.contrib.framework.python.ops import add_arg_scope
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import nn
from tensorflow.contrib.layers.python.layers import initializers
from tensorflow.contrib.layers.python.layers import utils
import nlp.wlayers as nlpl
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
import numpy as np
import time
from tensorflow.contrib.framework.python.ops import add_arg_scope
import basic_tftools as btf
from collections import Iterable
import wsummary
DATA_FORMAT_NHWC = 'NHWC'
slim = tf.contrib.slim
class ConvGRUCell(tf.nn.rnn_cell.RNNCell):
'''
shape: [H,W] net spatial shape
filters: filter size, which is the output channel num, e.g 128
kernel: kernel size, e.g [3,3]
'''
def __init__(self, shape, filters, kernel, activation=tf.tanh,
reuse=None):
super(ConvGRUCell, self).__init__(_reuse=reuse)
self._filters = filters
self._kernel = kernel
self._activation = activation
self._size = tf.TensorShape(shape + [self._filters])
self._feature_axis = self._size.ndims
self._data_format = None
@property
def state_size(self):
return self._size
@property
def output_size(self):
return self._size
def call(self, x, h):
#x's channel size
channels = x.shape[self._feature_axis].value
with tf.variable_scope('gates'):
inputs = tf.concat([x, h], axis=self._feature_axis)
n = channels + self._filters
#at lest output 2 channels
m = 2 * self._filters if self._filters > 1 else 2
#W's shape is spatial_filter_shape + [in_channels, out_channels]
W = tf.get_variable('kernel', self._kernel + [n, m])
y = tf.nn.convolution(inputs, W, 'SAME', data_format=self._data_format)
y += tf.get_variable('bias', [m], initializer=tf.ones_initializer())
r, u = tf.split(y, 2, axis=self._feature_axis)
r, u = tf.sigmoid(r), tf.sigmoid(u)
with tf.variable_scope('candidate'):
inputs = tf.concat([x, r * h], axis=self._feature_axis)
n = channels + self._filters
m = self._filters
W = tf.get_variable('kernel', self._kernel + [n, m])
y = tf.nn.convolution(inputs, W, 'SAME', data_format=self._data_format)
y += tf.get_variable('bias', [m], initializer=tf.zeros_initializer())
h = u * h + (1 - u) * self._activation(y)
return h, h
def separable_conv1d(inputs,num_outputs,kernel_size,padding='SAME',depth_multiplier=1,*args,**kwargs):
'''
:param inputs: [batch_size,W,C]
:param num_outputs: num
:param kernel_size: num
:param padding: 'SAME'/'VALID'
:return: [batch_size,W1,num_output]
'''
if padding == "SAME":
inputs = tf.pad(inputs,paddings=[[0,0],[kernel_size//2,kernel_size//2],[0,0]])
inputs = tf.expand_dims(inputs,axis=2)
res = slim.separable_conv2d(inputs,num_outputs,kernel_size=[kernel_size,1],padding="VALID",
depth_multiplier=depth_multiplier,*args,**kwargs)
return tf.squeeze(res,axis=2)
def probability_adjust(probs,classes=[]):
if probs.get_shape().ndims == 2:
return tfop.probability_adjust(probs=probs,classes=classes)
else:
old_shape = tf.shape(probs)
probs = tf.reshape(probs,[-1,old_shape[-1]])
out = tfop.probability_adjust(probs=probs,classes=classes)
out = tf.reshape(out,old_shape)
return out
def conv2d_batch_normal(input,decay=0.99,is_training=True,scale=False):
last_dim_size = input.get_shape().as_list()[-1]
with tf.variable_scope("BatchNorm"):
if scale:
gamma = tf.Variable(tf.ones([last_dim_size],tf.float32), name="gamma")
else:
gamma = None
offset = tf.Variable(tf.zeros([last_dim_size],tf.float32), name="beta")
moving_collections = ["bn_moving_vars",tf.GraphKeys.GLOBAL_VARIABLES, tf.GraphKeys.MOVING_AVERAGE_VARIABLES]
m_mean = tf.Variable(tf.zeros([last_dim_size],tf.float32),trainable=False,name="moving_mean",collections=moving_collections)
m_variance = tf.Variable(tf.ones([last_dim_size], tf.float32), trainable=False, name="moving_variance",collections=moving_collections)
if is_training:
c_mean, c_variance = tf.nn.moments(input, list(range(len(input.get_shape()) - 1)))
update_mean =moving_averages.assign_moving_average(m_mean,c_mean,decay)
update_variance = moving_averages.assign_moving_average(m_variance,c_variance,decay)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS,update_mean)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_variance)
else:
c_mean = m_mean
c_variance = m_variance
output = tf.nn.batch_normalization(input, c_mean, c_variance, offset, gamma, 1E-6, "BN")
return output
@add_arg_scope
def group_norm(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,offset=True,sub_mean=True,scope="group_norm",dtype=None):
assert scale==True or offset==True
C = x.get_shape().as_list()[-1]
assert C%G==0,f"Unmatch channel {C} and group {G} size"
if x.get_shape().ndims == 4:
return group_norm_4d_v1(x,G,epsilon,weights_regularizer=weights_regularizer,
scale=scale,
offset=offset,
sub_mean=sub_mean,
scope=scope,dtype=dtype)
elif x.get_shape().ndims == 2:
return group_norm_2d(x,G,epsilon,weights_regularizer=weights_regularizer,
scale=scale,
offset=offset,
sub_mean=sub_mean,
scope=scope,dtype=dtype)
else:
raise NotImplementedError
@add_arg_scope
def dynamic_group_norm(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,offset=True,sub_mean=True,scope="group_norm",dtype=None):
assert scale==True or offset==True
C = x.get_shape().as_list()[-1]
if C<G:
G = C
elif C%G != 0:
v = C//G
if C%v == 0:
G = C//v
else:
for i in range(1,C):
d0 = v-1
d1 = v+1
if d0>=1 and C%d0 == 0:
G = C//d0
break
elif d1<=C and C%d1 == 0:
G = C//d1
break
if x.get_shape().ndims == 4:
return group_norm_4d_v1(x,G,epsilon,weights_regularizer=weights_regularizer,
scale=scale,
offset=offset,
sub_mean=sub_mean,
scope=scope,dtype=dtype)
elif x.get_shape().ndims == 2:
return group_norm_2d(x,G,epsilon,weights_regularizer=weights_regularizer,
scale=scale,
offset=offset,
sub_mean=sub_mean,
scope=scope,dtype=dtype)
else:
raise NotImplementedError
@add_arg_scope
def group_norm_4d_v1(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,offset=True,sub_mean=True,scope="group_norm",dtype=None):
# x: input features with shape [N,H,W,C]
# gamma, beta: scale and offset, with shape [1,1,1,C] # G: number of groups for GN
with tf.variable_scope(scope):
N,H,W,C = btf.combined_static_and_dynamic_shape(x)
gamma = tf.get_variable(name="gamma",shape=[1,1,1,G,C//G],initializer=tf.ones_initializer(),dtype=dtype)
if offset:
beta = tf.get_variable(name="beta",shape=[1,1,1,G,C//G],initializer=tf.zeros_initializer(),dtype=dtype)
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(gamma))
x = wmlt.reshape(x, [N, H, W, G, C // G,])
mean, var = tf.nn.moments(x, [1, 2, 4], keep_dims=True)
gain = tf.math.rsqrt(var + epsilon)
if sub_mean:
offset_value = -mean * gain
else:
offset_value = None
if scale:
gain *= gamma
if offset_value is not None:
offset_value *= gamma
if offset:
if offset_value is None:
offset_value = beta
else:
offset_value += beta
if offset_value is not None:
x = x * gain + offset_value
else:
x = offset_value
x = wmlt.reshape(x, [N,H,W,C])
return x
@add_arg_scope
def group_norm_4d_v0(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,offset=True,scope="group_norm"):
# x: input features with shape [N,H,W,C]
# gamma, beta: scale and offset, with shape [1,1,1,C] # G: number of groups for GN
with tf.variable_scope(scope):
N,H,W,C = btf.combined_static_and_dynamic_shape(x)
gamma = tf.get_variable(name="gamma",shape=[1,1,1,C],initializer=tf.ones_initializer())
gamma = tf.reshape(gamma,[1,1,1,G,C//G])
beta = tf.get_variable(name="beta",shape=[1,1,1,C],initializer=tf.zeros_initializer())
beta = tf.reshape(beta,[1,1,1,G,C//G])
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(gamma))
x = wmlt.reshape(x, [N, H, W, G, C // G,])
mean, var = tf.nn.moments(x, [1, 2, 4], keep_dims=True)
gain = tf.math.rsqrt(var + epsilon)
if offset:
offset_value = -mean * gain
else:
offset_value = tf.zeros_like(beta)
if scale:
gain *= gamma
offset_value *= gamma
if offset:
offset_value += beta
x = x * gain + offset_value
x = wmlt.reshape(x, [N,H,W,C])
return x
@add_arg_scope
def group_norm_2d(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,offset=True,sub_mean=True,scope="group_norm",dtype=None):
with tf.variable_scope(scope):
N,C = x.get_shape().as_list()
gamma = tf.get_variable(name="gamma",shape=[1,G,C//G],initializer=tf.ones_initializer(),dtype=dtype)
if offset:
beta = tf.get_variable(name="beta",shape=[1,G,C//G],initializer=tf.zeros_initializer(),dtype=dtype)
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(gamma))
x = wmlt.reshape(x, [N,G, C // G,])
mean, var = tf.nn.moments(x, [2], keep_dims=True)
gain = tf.math.rsqrt(var+epsilon)
if sub_mean:
offset_value = -mean*gain
else:
offset_value = None
if scale:
gain *= gamma
if offset_value is not None:
offset_value *= gamma
if offset:
if offset_value is not None:
offset_value += beta
else:
offset_value = beta
x = x*gain+offset_value
x = wmlt.reshape(x, [N,C])
return x
@add_arg_scope
def group_norm_2d_v0(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,offset=True,scope="group_norm"):
with tf.variable_scope(scope):
N,C = x.get_shape().as_list()
gamma = tf.get_variable(name="gamma",shape=[1,C],initializer=tf.ones_initializer())
beta = tf.get_variable(name="beta",shape=[1,C],initializer=tf.zeros_initializer())
gamma = tf.reshape(gamma,[1,G,C//G])
beta = tf.reshape(beta,[1,G,C//G])
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(gamma))
x = wmlt.reshape(x, [N,G, C // G,])
mean, var = tf.nn.moments(x, [2], keep_dims=True)
gain = tf.math.rsqrt(var+epsilon)
offset_value = -mean*gain
if scale:
gain *= gamma
offset_value *= gamma
if offset:
offset += beta
x = x*gain+offset_value
x = wmlt.reshape(x, [N,C])
return x
@add_arg_scope
def group_norm_with_sn(x, G=32, epsilon=1e-5,scope="group_norm_with_sn",sn_iteration=1,max_sigma=None):
if x.get_shape().ndims == 4:
return group_norm_4d_with_sn(x,G,epsilon,scope=scope,sn_iteration=sn_iteration,max_sigma=max_sigma)
elif x.get_shape().ndims == 2:
return group_norm_2d_with_sn(x,G,epsilon,scope=scope,sn_iteration=sn_iteration,max_sigma=max_sigma)
@add_arg_scope
def group_norm_4d_with_sn(x, G=32, epsilon=1e-5,scope="group_norm_with_sn",sn_iteration=1,max_sigma=None):
# x: input features with shape [N,H,W,C]
# gamma, beta: scale and offset, with shape [1,1,1,C] # G: number of groups for GN
with tf.variable_scope(scope):
if x.get_shape().is_fully_defined():
N,H,W,C = x.get_shape().as_list()
else:
none_nr = 0
for v in x.get_shape().as_list():
if v is None:
none_nr += 1
if none_nr>1:
N, H, W, _ = tf.unstack(tf.shape(x),axis=0)
C = x.get_shape().as_list()[-1]
else:
N,H,W,C = x.get_shape().as_list()
gamma = tf.get_variable(name="gamma",shape=[1,1,1,C],initializer=tf.ones_initializer())
beta = tf.get_variable(name="beta",shape=[1,1,1,C],initializer=tf.zeros_initializer())
x = wmlt.reshape(x, [N, H, W, G, C // G,])
mean, var = tf.nn.moments(x, [1, 2, 4], keep_dims=True)
x = (x - mean) / tf.sqrt(var + epsilon)
x = wmlt.reshape(x, [N,H,W,C])
return x*spectral_norm(gamma,sn_iteration,max_sigma=max_sigma) + beta
@add_arg_scope
def group_norm_2d_with_sn(x, G=32, epsilon=1e-5,scope="group_norm_with_sn",sn_iteration=1,max_sigma=None):
with tf.variable_scope(scope):
N,C = x.get_shape().as_list()
gamma = tf.get_variable(name="gamma",shape=[1,C],initializer=tf.ones_initializer())
beta = tf.get_variable(name="beta",shape=[1,C],initializer=tf.zeros_initializer())
x = wmlt.reshape(x, [N,G, C // G,])
mean, var = tf.nn.moments(x, [2], keep_dims=True)
x = (x - mean) / tf.sqrt(var + epsilon)
x = wmlt.reshape(x, [N,C])
return x*spectral_norm(gamma,sn_iteration,max_sigma=max_sigma)+ beta
@add_arg_scope
def group_norm_v2(x, gamma=None,beta=None,G=32, epsilon=1e-5,weights_regularizer=None,scale=True,offset=True,sub_mean=True,scope=None,dtype=None):
# x: input features with shape [N,H,W,C]
# gamma, beta: scale and offset, with shape [1,1,1,C] # G: number of groups for GN
with tf.variable_scope(scope,default_name="group_norm_v2"):
N,H,W,C = btf.combined_static_and_dynamic_shape(x)
if gamma is not None:
gamma = tf.reshape(gamma,shape=[N,1,1,G,C//G])
if beta is not None:
beta = tf.reshape(beta,shape=[N,1,1,G,C//G])
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(gamma))
x = wmlt.reshape(x, [N, H, W, G, C // G,])
mean, var = tf.nn.moments(x, [1, 2, 4], keep_dims=True)
gain = tf.math.rsqrt(var + epsilon)
if sub_mean:
offset_value = -mean * gain
else:
offset_value = None
if scale:
gain *= gamma
if offset_value is not None:
offset_value *= gamma
if offset:
if offset_value is None:
offset_value = beta
else:
offset_value += beta
if offset_value is not None:
x = x * gain + offset_value
else:
x = offset_value
x = wmlt.reshape(x, [N,H,W,C])
return x
@add_arg_scope
def evo_norm_s0(x,*args,**kwargs):
if len(x.get_shape()) == 4:
return evo_norm_s0_4d(x,*args,**kwargs)
elif len(x.get_shape())==2:
return evo_norm_s0_2d(x,*args,**kwargs)
else:
raise NotImplementedError(f"Input dims must be 2 or 4.")
@add_arg_scope
def dynamic_evo_norm_s0(x,G=32,*args,**kwargs):
C = x.get_shape().as_list()[-1]
if C<G:
G = C
elif C%G != 0:
v = C//G
if C%v == 0:
G = C//v
else:
for i in range(1,C):
d0 = v-1
d1 = v+1
if d0>=1 and C%d0 == 0:
G = C//d0
break
elif d1<=C and C%d1 == 0:
G = C//d1
break
if len(x.get_shape()) == 4:
return evo_norm_s0_4d(x,G=G,*args,**kwargs)
elif len(x.get_shape())==2:
return evo_norm_s0_2d(x,G=G,*args,**kwargs)
else:
raise NotImplementedError(f"Input dims must be 2 or 4.")
@add_arg_scope
def evo_norm_s0_4d(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,scope="evo_norm_s0"):
# x: input features with shape [N,H,W,C]
# gamma, beta: scale with shape [1,1,1,C] # G: number of groups for GN
# WARNING: after evo_norm_s0, there is no need to append a activation fn.
with tf.variable_scope(scope):
N,H,W,C = btf.combined_static_and_dynamic_shape(x)
gamma = tf.get_variable(name="gamma",shape=[1,1,1,G,C//G],initializer=tf.ones_initializer())
beta = tf.get_variable(name="beta",shape=[1,1,1,G,C//G],initializer=tf.zeros_initializer())
v1 = tf.get_variable(name="v1",shape=[1,1,1,G,C//G],initializer=tf.ones_initializer())
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(gamma))
assert C%G==0,f"Error C={C}, G={G}"
x = wmlt.reshape(x, [N, H, W, G, C // G,])
mean, var = tf.nn.moments(x, [1, 2, 4], keep_dims=True)
gain = tf.math.rsqrt(var + epsilon)
if scale:
gain *= gamma
x = x * tf.nn.sigmoid(x*v1)*gain + beta
x = wmlt.reshape(x, [N,H,W,C])
return x
@add_arg_scope
def evo_norm_s0_2d(x, G=32, epsilon=1e-5,weights_regularizer=None,scale=True,scope="evo_norm_s0"):
# x: input features with shape [N,H,W,C]
# gamma, beta: scale with shape [1,1,1,C] # G: number of groups for GN
# WARNING: after evo_norm_s0, there is no need to append a activation fn.
with tf.variable_scope(scope):
N,C = btf.combined_static_and_dynamic_shape(x)
gamma = tf.get_variable(name="gamma",shape=[1,G,C//G],initializer=tf.ones_initializer())
beta = tf.get_variable(name="beta",shape=[1,G,C//G],initializer=tf.zeros_initializer())
v1 = tf.get_variable(name="v1",shape=[1,G,C//G],initializer=tf.ones_initializer())
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(gamma))
assert C%G==0,f"Error C={C}, G={G}"
x = wmlt.reshape(x, [N, G, C // G,])
mean, var = tf.nn.moments(x, [2], keep_dims=True)
gain = tf.math.rsqrt(var + epsilon)
if scale:
gain *= gamma
x = x * tf.nn.sigmoid(x*v1)*gain + beta
x = wmlt.reshape(x, [N,C])
return x
@add_arg_scope
def spectral_norm_for_conv(x,is_training=True,scope=None):
#用于normalizer的conv2d, full_connected的权重名为weights并且需要与本函数在同一个value_scope中
def get_weights():
ws = tf.trainable_variables(tf.get_variable_scope().name)
res = None
total_nr = 0
for w in ws:
if w.name.endswith("weights:0"):
res = w
total_nr += 1
assert total_nr==1,"error weights nr."
return res
w = get_weights()
B,H,W,C = x.get_shape().as_list()
with tf.variable_scope(scope,"spectral_norm"):
beta = tf.get_variable(name="beta", shape=[1, 1, 1, C], initializer=tf.ones_initializer())
gamma = tf.get_variable(name="gamma", shape=[1, 1, 1, C], initializer=tf.ones_initializer())
s_sigma = tf.get_variable("sigma", (), initializer=tf.ones_initializer(), trainable=not is_training)
if is_training:
w_shape = w.shape.as_list()
w = tf.reshape(w, [-1, w_shape[-1]])
u = tf.get_variable("u", [1, w_shape[-1]], initializer=tf.random_normal_initializer(), trainable=False)
with tf.name_scope("get_sigma"):
u_hat = u
#one iterator
v_ = tf.matmul(u_hat, tf.transpose(w))
v_hat = tf.nn.l2_normalize(v_)
u_ = tf.matmul(v_hat, w)
u_hat = tf.nn.l2_normalize(u_)
u_hat = tf.stop_gradient(u_hat)
v_hat = tf.stop_gradient(v_hat)
sigma = tf.reshape(tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat)),())
with tf.control_dependencies([u.assign(u_hat),s_sigma.assign(sigma)]):
v = gamma/sigma
x = x*v+beta
else:
v = gamma /s_sigma
x = x * v+beta
return x
@add_arg_scope
def layer_norm(x,scope="layer_norm"):
return tf.contrib.layers.layer_norm(
inputs=x, begin_norm_axis=-1, begin_params_axis=-1, scope=scope)
def graph_norm(input,decay=0.99,scale=True):
last_dim_size = input.get_shape().as_list()[-1]
with tf.variable_scope("BatchNorm"):
if scale:
gamma = tf.get_variable(name="gamma",shape=(last_dim_size),initializer=tf.ones_initializer())
else:
gamma = None
offset = tf.get_variable(name="beta",shape=(last_dim_size),initializer=tf.zeros_initializer())
c_mean, c_variance = tf.nn.moments(input, list(range(len(input.get_shape()) - 1)))
'''wsummary.variable_summaries_v2(c_mean, "graph_norm_mean", "layer_norm")
wsummary.variable_summaries_v2(c_variance, "graph_norm_variance", "layer_norm")
wsummary.variable_summaries_v2(input, "net", "net")'''
output = tf.nn.batch_normalization(input, c_mean, c_variance, offset, gamma, 1E-6, "BN")
return output
def group_graph_norm(x,G=16,decay=0.99,scale=True,offset=True,epsilon=1e-8):
with tf.variable_scope("group_graph_norm"):
dtype = x.dtype
N,C = wmlt.combined_static_and_dynamic_shape(x)
gamma = tf.get_variable(name="gamma",shape=[1,G,C//G],initializer=tf.ones_initializer(),dtype=dtype)
if offset:
beta = tf.get_variable(name="beta",shape=[1,G,C//G],initializer=tf.zeros_initializer(),dtype=dtype)
x = wmlt.reshape(x, [N,G, C // G,])
mean, var = tf.nn.moments(x, [0,2], keep_dims=True)
gain = tf.math.rsqrt(var+epsilon)
offset_value = -mean*gain
if scale:
gain *= gamma
if offset_value is not None:
offset_value *= gamma
if offset:
if offset_value is not None:
offset_value += beta
else:
offset_value = beta
x = x*gain+offset_value
x = wmlt.reshape(x, [N,C])
return x
return output
@add_arg_scope
def instance_norm(x, eps=1e-5):
with tf.variable_scope("layer_norm"):
N, H, W, C = x.shape
gamma = tf.get_variable(name="gamma",shape=(1,1,1,C),initializer=tf.ones_initializer())
beta = tf.get_variable(name="beta",shape=(1,1,1,C),initializer=tf.zeros_initializer())
mean, var = tf.nn.moments(x, [2, 3], keep_dims=True)
x = (x - mean) / tf.sqrt(var + eps)
return x*gamma + beta
def gelu(x):
cdf = 0.5 * (1.0 + tf.erf(x/ tf.sqrt(2.0)))
return x* cdf
#return 0.5*x*(1+tf.tanh(math.sqrt(2/math.pi)*(x+0.044715*tf.pow(x, 3))))
def h_swish(x):
with tf.name_scope("h_swish"):
return x*tf.nn.relu6(x+3)/6.0
def mish(x):
with tf.name_scope("mish"):
return x*tf.tanh(tf.nn.softplus(x))
@add_arg_scope
def spectral_norm(w, iteration=1,max_sigma=None,is_training=True,scope=None,dtype=None):
with tf.variable_scope(scope,"spectral_norm"):
w_shape = w.shape.as_list()
s_w = tf.get_variable("sn_weight",w_shape,initializer=tf.zeros_initializer,trainable=False,dtype=dtype)
if is_training:
s_sigma = tf.get_variable("sigma",(),initializer=tf.ones_initializer(),trainable=False,dtype=dtype)
w_shape = w.shape.as_list()
w = tf.reshape(w, [-1, w_shape[-1]])
u = tf.get_variable("u", [1, w_shape[-1]], initializer=tf.random_normal_initializer(), trainable=False,dtype=dtype)
u_hat = u
v_hat = None
for i in range(iteration):
"""
power iteration
Usually iteration = 1 will be enough
"""
v_ = tf.matmul(u_hat, tf.transpose(w))
v_hat = tf.nn.l2_normalize(v_)
u_ = tf.matmul(v_hat, w)
u_hat = tf.nn.l2_normalize(u_)
u_hat = tf.stop_gradient(u_hat)
v_hat = tf.stop_gradient(v_hat)
sigma = tf.reshape(tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat)),())
with tf.control_dependencies([u.assign(u_hat),s_sigma.assign(sigma)]):
if max_sigma is None:
w_norm = w / sigma
else:
w_norm = w/(sigma/max_sigma)
w_norm = tf.reshape(w_norm, w_shape)
with tf.control_dependencies([s_w.assign(w_norm)]):
w_norm = tf.identity(w_norm)
else:
w_norm = s_w
return w_norm
@add_arg_scope
def conv2d_with_sn(inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
activation_fn=nn.relu,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
normalizer_fn=None,
normalizer_params=None,
outputs_collections=None,
rate=1,
reuse=None,
scope=None,sn_iteration=1,dtype=None):
del rate
print(f"conv2d_with_sn is deprecated.")
with variable_scope.variable_scope(scope, 'conv2d', [inputs], reuse=reuse) as sc:
if isinstance(kernel_size,list):
shape = kernel_size+[inputs.get_shape().as_list()[-1],num_outputs]
else:
shape = [kernel_size,kernel_size,inputs.get_shape().as_list()[-1],num_outputs]
w = tf.get_variable("kernel", shape=shape,
initializer=weights_initializer,dtype=dtype)
b = tf.get_variable("bias", [num_outputs], initializer=biases_initializer,dtype=dtype)
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(w))
if biases_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,biases_regularizer(b))
outputs = tf.nn.conv2d(input=inputs, filter=spectral_norm(w,iteration=sn_iteration,dtype=dtype),
strides=[1, stride, stride, 1],
padding=padding) + b
if normalizer_fn is not None:
if normalizer_params is None:
normalizer_params = {}
outputs = normalizer_fn(outputs,**normalizer_params)
if activation_fn is not None:
outputs = utils.collect_named_outputs(outputs_collections, sc.name+"_pre_act", outputs)
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
@add_arg_scope
def conv2d_with_sn_v2(inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
activation_fn=nn.relu,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
normalizer_fn=None,
normalizer_params=None,
outputs_collections=None,
rate=1,
reuse=None,
scope=None,sn_iteration=1):
del rate
with variable_scope.variable_scope(scope, 'conv2d', [inputs], reuse=reuse) as sc:
if isinstance(kernel_size,list):
shape = kernel_size+[inputs.get_shape().as_list()[-1],num_outputs]
else:
shape = [kernel_size,kernel_size,inputs.get_shape().as_list()[-1],num_outputs]
w = tf.get_variable("kernel", shape=shape,
initializer=weights_initializer)
if biases_initializer is not None and normalizer_fn is None:
b = tf.get_variable("bias", [num_outputs], initializer=biases_initializer)
else:
b = None
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(w))
if b is not None and biases_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,biases_regularizer(b))
outputs = tf.nn.conv2d(input=inputs, filter=spectral_norm(w,iteration=sn_iteration), strides=[1, stride, stride, 1],padding=padding)
if b is not None:
outputs = outputs + b
if normalizer_fn is not None:
if normalizer_params is None:
normalizer_params = {}
outputs = normalizer_fn(outputs,**normalizer_params)
if activation_fn is not None:
outputs = utils.collect_named_outputs(outputs_collections, sc.name+"_pre_act", outputs)
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
@add_arg_scope
def depthwise_conv2d_with_sn(inputs,
kernel_size,
stride=1,
padding='SAME',
activation_fn=nn.relu,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
normalizer_fn=None,
normalizer_params=None,
outputs_collections=None,
rate=1,
reuse=None,
scope=None,sn_iteration=1):
del rate
with variable_scope.variable_scope(scope, 'conv2d', [inputs], reuse=reuse) as sc:
num_inputs = inputs.get_shape().as_list()[-1]
if isinstance(kernel_size,list):
shape = kernel_size+[num_inputs,1]
else:
shape = [kernel_size,kernel_size,num_inputs,1]
w = tf.get_variable("kernel", shape=shape,
initializer=weights_initializer)
if biases_initializer is not None and normalizer_fn is None:
b = tf.get_variable("bias", [num_inputs], initializer=biases_initializer)
else:
b = None
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(w))
if b is not None and biases_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,biases_regularizer(b))
outputs = tf.nn.depthwise_conv2d(input=inputs, filter=spectral_norm(w,iteration=sn_iteration),
strides=[1, stride, stride, 1],padding=padding)
if normalizer_fn is not None:
if normalizer_params is None:
normalizer_params = {}
outputs = normalizer_fn(outputs,**normalizer_params)
elif b is not None:
outputs = outputs + tf.reshape(b,[1,1,1,num_inputs])
if activation_fn is not None:
outputs = activation_fn(outputs)
if outputs_collections is not None:
return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
else:
return outputs
@add_arg_scope
def separable_conv2d_with_sn(inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
activation_fn=nn.relu,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
normalizer_fn=None,
normalizer_params=None,
outputs_collections=None,
rate=1,
reuse=None,
scope=None):
with tf.variable_scope(scope,default_name="separable_conv2d_with_sn",reuse=reuse) as sc:
net = depthwise_conv2d_with_sn(inputs,kernel_size=kernel_size,
stride=stride,
padding=padding,
activation_fn=None,
weights_initializer=weights_initializer,
weights_regularizer=weights_regularizer,
biases_initializer=None,
normalizer_fn=None,
outputs_collections=outputs_collections,
rate=rate,
)
if num_outputs is not None:
net = conv2d_with_sn(net,num_outputs,kernel_size=[1,1],
padding="SAME",
activation_fn=None,
normalizer_fn=None,
weights_initializer=weights_initializer,
outputs_collections=outputs_collections)
b = None
if normalizer_fn is not None:
if normalizer_params is None:
normalizer_params = {}
net = normalizer_fn(net, **normalizer_params)
else:
if biases_initializer is not None:
b = tf.get_variable("bias", [num_outputs], initializer=biases_initializer)
if b is not None and biases_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,biases_regularizer(b))
if b is not None:
b = tf.reshape(b,[1,1,1,num_outputs])
net = net + b
if activation_fn is not None:
net = activation_fn(net)
if outputs_collections is not None:
return utils.collect_named_outputs(outputs_collections, sc.name, net)
else:
return net
@add_arg_scope
def fully_connected_with_sn(inputs,
num_outputs,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None,sn_iteration=1,dtype=None):
with tf.variable_scope(scope,
'fully_connected', [inputs], reuse=reuse) as sc:
shape = inputs.get_shape().as_list()
channels = shape[-1]
w = tf.get_variable("weights", [channels, num_outputs],
initializer=weights_initializer,
regularizer=weights_regularizer,trainable=trainable,
collections=variables_collections,dtype=dtype)
if weights_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,weights_regularizer(w))
if biases_initializer is not None:
b = tf.get_variable("biases", [num_outputs],
initializer=biases_initializer,
regularizer=biases_regularizer,trainable=trainable,
collections=variables_collections,dtype=dtype)
if biases_regularizer is not None:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES,biases_regularizer(b))
outputs = tf.matmul(inputs,spectral_norm(w,iteration=sn_iteration,dtype=dtype))+b
else:
outputs = tf.matmul(inputs,spectral_norm(w,iteration=sn_iteration,dtype=dtype))
# Apply normalizer function / layer.
if normalizer_fn is not None:
if not normalizer_params:
normalizer_params = {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
def orthogonal_initializer(shape, dtype=tf.float32, *args, **kwargs):
"""Generates orthonormal matrices with random values.
Orthonormal initialization is important for RNNs:
http://arxiv.org/abs/1312.6120
http://smerity.com/articles/2016/orthogonal_init.html
For non-square shapes the returned matrix will be semi-orthonormal: if the
number of columns exceeds the number of rows, then the rows are orthonormal
vectors; but if the number of rows exceeds the number of columns, then the
columns are orthonormal vectors.
We use SVD decomposition to generate an orthonormal matrix with random
values. The same way as it is done in the Lasagne library for Theano. Note
that both u and v returned by the svd are orthogonal and random. We just need
to pick one with the right shape.
Args:
shape: a shape of the tensor matrix to initialize.
dtype: a dtype of the initialized tensor.
*args: not used.
**kwargs: not used.
Returns:
An initialized tensor.
"""
del args
del kwargs
flat_shape = (shape[0], np.prod(shape[1:]))
w = np.random.randn(*flat_shape)
u, _, v = np.linalg.svd(w, full_matrices=False)
w = u if u.shape == flat_shape else v
return tf.constant(w.reshape(shape), dtype=dtype)
def non_local_block(net,multiplier=0.5,n_head=1,keep_prob=None,is_training=False,scope=None):
def reshape_net(net):
shape = net.get_shape().as_list()
new_shape = [-1,shape[1]*shape[2],shape[3]]
net = tf.reshape(net,new_shape)
return net
def restore_shape(net,shape,channel):
out_shape = [-1,shape[1],shape[2],channel]
net = tf.reshape(net,out_shape)
return net
with tf.variable_scope(scope,default_name="non_local"):
shape = net.get_shape().as_list()
channel = shape[-1]
m_channel = int(channel*multiplier)
Q = slim.conv2d(net,m_channel,[1,1],activation_fn=None)
K = slim.conv2d(net,m_channel,[1,1],activation_fn=None)
V = slim.conv2d(net,m_channel,[1,1],activation_fn=None)
Q = reshape_net(Q)
K = reshape_net(K)
V = reshape_net(V)
out = nlpl.multi_head_attention(Q, K, V, n_head=n_head,keep_prob=keep_prob, is_training=is_training,
use_mask=False)
out = restore_shape(out,shape,m_channel)
out = slim.conv2d(out,channel,[1,1],activation_fn=None,
weights_initializer=tf.zeros_initializer)
return net+out
def non_local_blockv1(net,inner_dims_multiplier=[8,8,2],
inner_dims=None,
n_head=1,keep_prob=None,is_training=False,scope=None,
conv_op=slim.conv2d,pool_op=None,normalizer_fn=slim.batch_norm,normalizer_params=None,
activation_fn=tf.nn.relu,
gamma_initializer=tf.constant_initializer(0.0),reuse=None,
weighed_sum=True):
def reshape_net(net):
shape = wmlt.combined_static_and_dynamic_shape(net)
new_shape = [shape[0],shape[1]*shape[2],shape[3]]
net = tf.reshape(net,new_shape)
return net
def restore_shape(net,shape,channel):
out_shape = [shape[0],shape[1],shape[2],channel]
net = tf.reshape(net,out_shape)
return net
if isinstance(inner_dims_multiplier,int):
inner_dims_multiplier = [inner_dims_multiplier]
if len(inner_dims_multiplier) == 1:
inner_dims_multiplier = inner_dims_multiplier*3
if inner_dims is not None:
if isinstance(inner_dims, int):
inner_dims = [inner_dims]
if len(inner_dims) == 1:
inner_dims = inner_dims*3
with tf.variable_scope(scope,default_name="non_local",reuse=reuse):
shape = wmlt.combined_static_and_dynamic_shape(net)
channel = shape[-1]
if inner_dims is not None:
m_channelq = inner_dims[0]
m_channelk = inner_dims[1]
m_channelv = inner_dims[2]
pass
else:
m_channelq = channel//inner_dims_multiplier[0]
m_channelk = channel//inner_dims_multiplier[1]
m_channelv = channel//inner_dims_multiplier[2]
Q = conv_op(net,m_channelq,[1,1],activation_fn=None,normalizer_fn=None,scope="q_conv")
K = conv_op(net,m_channelk,[1,1],activation_fn=None,normalizer_fn=None,scope="k_conv")
V = conv_op(net,m_channelv,[1,1],activation_fn=None,normalizer_fn=None,scope="v_conv")
if pool_op is not None:
K = pool_op(K,kernel_size=2, stride=2,padding="SAME")
V = pool_op(V,kernel_size=2, stride=2,padding="SAME")
Q = reshape_net(Q)
K = reshape_net(K)
V = reshape_net(V)
out = nlpl.multi_head_attention(Q, K, V, n_head=n_head,keep_prob=keep_prob, is_training=is_training,
use_mask=False)
out = restore_shape(out,shape,m_channelv)
out = conv_op(out,channel,[1,1],
activation_fn=None,
normalizer_fn=None,
scope="attn_conv")