-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlayers.py
executable file
·1160 lines (979 loc) · 41.5 KB
/
layers.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
# 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
#
# https://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.
"""Custom neural network layers.
Low-level primitives such as custom convolution with custom initialization.
"""
from __future__ import division
from __future__ import print_function
import functools
import numpy as np
import tensorflow as tf
from tensorflow.python.eager import def_function
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.utils import conv_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import nn_ops
NCHW, NHWC = ('NCHW', 'NHWC')
# -----------------------------------------------------------------------------
# OPs / functions (those don't use any trainable variables).
# -----------------------------------------------------------------------------
def _check_order(order):
if order not in (NCHW, NHWC):
raise ValueError('Unsupported tensor order: %s.' % order)
def blur_pool(x, blur_filter=(1., 2., 1.), normalize=True, order=NHWC):
"""TBD."""
blur_filter = np.array(blur_filter)
if blur_filter.ndim == 1:
blur_filter = blur_filter[:, np.newaxis] * blur_filter[np.newaxis, :]
if normalize:
blur_filter /= np.sum(blur_filter)
blur_filter = blur_filter[:, :, np.newaxis, np.newaxis]
blur_filter = tf.constant(blur_filter, dtype=tf.float32)
channels = x.shape[1] if order == NCHW else x.shape[-1]
blur_filter = tf.tile(blur_filter, [1, 1, channels, 1])
strides = (1, 1, 2, 2) if order == NCHW else (1, 2, 2, 1)
return tf.nn.depthwise_conv2d(
input=x,
filter=blur_filter,
strides=strides,
padding='SAME')
def downscale2d(x, n=2, pool_type='average', order=NHWC):
"""Box downscaling.
Args:
x: 4D tensor in order format.
n: integer scale.
pool_type: String, pooling method; one of {average, blur}.
order: enum(NCHW, NHWC), the order of channels vs dimensions.
Returns:
4D tensor down scaled by a factor n.
Raises:
ValueError: if order not NCHW or NHWC.
"""
_check_order(order)
assert pool_type in ['average', 'blur']
if n <= 1:
return x
if order == NCHW:
pool2, pooln = [1, 1, 2, 2], [1, 1, n, n]
else:
pool2, pooln = [1, 2, 2, 1], [1, n, n, 1]
if n % 2 == 0:
if pool_type == 'average':
x = tf.nn.avg_pool2d(x, pool2, pool2, 'VALID', order)
elif pool_type == 'blur':
x = blur_pool(x, order=order)
return downscale2d(x, n // 2, order=order)
# This shouldn't usually happen, unleas the downscale factor is odd and >= 3!
return tf.nn.avg_pool2d(x, pooln, pooln, 'VALID', order)
def _upscale2d(x, n=2, order=NHWC):
"""Box upscaling (also called nearest neighbors).
Args:
x: 4D tensor in order format.
n: integer scale (must be a power of 2).
order: enum(NCHW, NHWC), the order of channels vs dimensions.
Returns:
4D tensor up scaled by a factor n.
Raises:
ValueError: if order not NCHW or NHWC.
"""
_check_order(order)
if n == 1:
return x
s = x.shape
if order == NCHW:
x = tf.reshape(x, [-1, s[1], s[2], s[3], 1])
x = tf.tile(x, [1, 1, 1, n, n])
x = tf.reshape(x, [-1, s[1], s[2] * n, s[3] * n])
else:
x = tf.tile(x, [1, 1, n, n])
x = tf.reshape(x, [-1, s[1] * n, s[2] * n, s[3]])
return x
def global_avg_pooling(x, keepdims=True, order=NHWC):
"""TBD"""
axis = [2, 3] if order == NCHW else [1, 2]
return tf.reduce_mean(x, axis=axis, keepdims=keepdims)
def flatten_spatial_dimensions(tensor, order=NHWC):
"""TBD"""
assert order == NHWC, 'NCHW not yet supported (TBD).'
batch_size = tf.dimension_value(tensor.shape[0])
nc = tf.dimension_value(tensor.shape[-1])
return tf.reshape(tensor, shape=(batch_size, -1, nc))
def remove_details2d(x, n=2, order=NHWC):
"""Removes box details by upscaling a downscaled image.
Args:
x: 4D tensor in order format.
n: integer scale (must be a power of 2).
order: enum(NCHW, NHWC), the order of channels vs dimensions.
Returns:
4D tensor image with removed details of size nxn.
"""
if n == 1:
return x
return _upscale2d(downscale2d(x, n, order=order), n, order=order)
def blend_resolution(lores, hires, alpha):
"""Blends two images.
Args:
lores: 4D tensor, low resolution image.
hires: 4D tensor, high resolution image.
alpha: scalar tensor, 0 produces the low resolution, 1 the high one.
Returns:
4D tensor of blended images.
"""
return lores + alpha * (hires - lores)
def _kaiming_scale(shape):
# Shape is [kernel, kernel, fmaps_in, fmaps_out] or [in, out] for Conv/Dense.
fan_in = np.prod(shape[:-1])
return 1. / np.sqrt(fan_in)
# -----------------------------------------------------------------------------
# Custom keras initializers. (experimental)
# -----------------------------------------------------------------------------
class GlorotNormalInitializerWithGain(tf.keras.initializers.GlorotNormal):
def __init__(self, gain=0.02, **kwargs):
super(GlorotNormalInitializerWithGain, self).__init__(**kwargs)
self.gain = gain
def __call__(self, *args, **kwargs):
weights = super(GlorotNormalInitializerWithGain, self).__call__(
*args, **kwargs)
return self.gain * weights
# -----------------------------------------------------------------------------
# Custom keras layers.
# -----------------------------------------------------------------------------
class ResBlock(tf.keras.layers.Layer):
"""Convolution block with resisudal connections (e.g. described in BigGAN)."""
def __init__(self, fin, fout, conv_layer, act_layer, norm_layer, name=None,
order=NHWC, simulate_shortcut_norm_bug=False,
add_spatial_noise=False, **kwargs):
super(ResBlock, self).__init__(name=name, **kwargs)
f_middle = min(fin, fout)
def _create_conv_block(num_filters, kernel_size, use_bias=True,
apply_norm=True, apply_activation=True,
block_name=None):
"""TBD."""
conv_block = tf.keras.Sequential(name=block_name)
if add_spatial_noise:
conv_block.add(StyleGANSpatialNoise(name='spatial_noise', order=order))
if (apply_norm or simulate_shortcut_norm_bug) and norm_layer is not None:
conv_block.add(norm_layer())
if apply_activation:
conv_block.add(act_layer())
conv_block.add(
conv_layer(filters=num_filters, kernel_size=kernel_size,
use_bias=use_bias, activation=None, name='conv2d'))
return conv_block
if fin != fout:
self.shortcut = _create_conv_block(
fout, 1, use_bias=False, apply_norm=False, apply_activation=False,
block_name='Shortuct')
else:
self.shortcut = None
self.conv_block0 = _create_conv_block(f_middle, 3, block_name='Conv0')
self.conv_block1 = _create_conv_block(fout, 3, block_name='Conv1')
def call(self, inputs, spatial_noise=None, training=None):
if self.shortcut is not None:
x_shortcut = self.shortcut(inputs, training=training)
else:
x_shortcut = inputs
x = self.conv_block0(inputs, training=training)
x = self.conv_block1(x, training=training)
return x + x_shortcut
class ResBlockDown(tf.keras.layers.Layer):
"""Convolution downsample resblock (e.g. described in BigGAN)."""
def __init__(self, fout, conv_layer, act_layer, norm_layer,
pool_type='average', mul_factor=1., name=None, order=NHWC,
**kwargs):
super(ResBlockDown, self).__init__(name=name, **kwargs)
self.fout = fout
self.conv_layer = conv_layer
self.act_layer = act_layer
self.norm_layer = norm_layer
self.pool_type = pool_type
self.mul_factor = mul_factor
self.order = order
def build(self, input_shape):
fin = input_shape[-1] if self.order == NHWC else input_shape[1]
# Shortcut conv (no bias).
self.conv_shortcut = self.conv_layer(
filters=self.fout, kernel_size=1, use_bias=False, activation=None,
name='conv_shortcut')
# Conv block #0.
self.norm0 = self.norm_layer() if self.norm_layer is not None else None
self.act0 = self.act_layer()
self.conv0 = self.conv_layer(filters=fin, kernel_size=3,
use_bias=True, activation=None, name='Conv0')
# Conv block #1.
self.norm1 = self.norm_layer() if self.norm_layer is not None else None
self.act1 = self.act_layer()
self.conv1 = self.conv_layer(filters=self.fout, kernel_size=3,
use_bias=True, activation=None, name='Conv1')
# Downsampling layer/function.
self.downsample2d = functools.partial(
downscale2d, n=2, pool_type=self.pool_type, order=self.order)
super(ResBlockDown, self).build(input_shape)
def _maybe_normalize(self, apply_norm_fn, x, z_style, training):
"""Applies standard normalization or adaptive instance normalization (AdaIN), if any."""
if apply_norm_fn is None:
return x
else:
inputs = [x, z_style] if z_style is not None else x
return apply_norm_fn(inputs, training=training)
def call(self, inputs, z_style=None, training=None):
x_shortcut = self.conv_shortcut(inputs, training=training)
x_shortcut = self.downsample2d(x_shortcut)
x = inputs
x = self._maybe_normalize(self.norm0, x, z_style, training=training)
x = self.act0(x)
x = self.conv0(x, training=training)
x = self._maybe_normalize(self.norm1, x, z_style, training=training)
x = self.act1(x)
x = self.conv1(x, training=training)
x = self.downsample2d(x)
return (x + x_shortcut) * self.mul_factor
class ResBlockUp(tf.keras.layers.Layer):
"""Convolution upsample resblock (e.g. described in BigGAN)."""
def __init__(self, fout, conv_layer, act_layer, norm_layer,
interpolation='bilinear', name=None, order=NHWC, **kwargs):
super(ResBlockUp, self).__init__(name=name, **kwargs)
self.fout = fout
self.conv_layer = conv_layer
self.act_layer = act_layer
self.norm_layer = norm_layer
self.interpolation = interpolation
self.order = order
def build(self, input_shape):
# Shortcut conv (no bias).
self.conv_shortcut = self.conv_layer(
filters=self.fout, kernel_size=1, use_bias=False, activation=None,
name='conv_shortcut')
# Conv block #0.
self.norm0 = self.norm_layer() if self.norm_layer is not None else None
self.act0 = self.act_layer()
self.conv0 = self.conv_layer(filters=self.fout, kernel_size=3,
use_bias=True, activation=None, name='Conv0')
# Conv block #1.
self.norm1 = self.norm_layer() if self.norm_layer is not None else None
self.act1 = self.act_layer()
self.conv1 = self.conv_layer(filters=self.fout, kernel_size=3,
use_bias=True, activation=None, name='Conv1')
# Upsampling layer/function.
data_format = 'channels_last' if self.order == NHWC else 'channels_last'
self.upsample2d = tf.keras.layers.UpSampling2D(
size=2, interpolation=self.interpolation, data_format=data_format)
super(ResBlockUp, self).build(input_shape)
def _maybe_normalize(self, apply_norm_fn, x, z_style, training):
if apply_norm_fn is None:
return x
else:
inputs = [x, z_style] if z_style is not None else x
return apply_norm_fn(inputs, training=training)
def call(self, inputs, z_style=None, training=None):
x_shortcut = self.upsample2d(inputs)
x_shortcut = self.conv_shortcut(x_shortcut, training=training)
x = inputs
x = self._maybe_normalize(self.norm0, x, z_style, training=training)
x = self.act0(x)
x = self.upsample2d(x)
x = self.conv0(x, training=training)
x = self._maybe_normalize(self.norm1, x, z_style, training=training)
x = self.act1(x)
x = self.conv1(x, training=training)
return x + x_shortcut
class SPADEConvBlock(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, pre_norm_layer, act_layer, conv_layer, fout,
spade_norm_conv_layer, projection_filters=128, kernel_size=3,
use_bias=True, name=None, order=NHWC, **kwargs):
super(SPADEConvBlock, self).__init__(**kwargs)
self.spade_norm = SPADENormalization(
pre_norm_layer,
spade_norm_conv_layer,
projection_filters=projection_filters,
order=order,
**kwargs)
self.activation = act_layer() if act_layer is not None else None
self.conv = conv_layer(
filters=fout, kernel_size=kernel_size, strides=1, padding='SAME',
use_bias=use_bias, activation=None,
data_format='channels_last' if order == NHWC else 'channels_first')
def call(self, inputs, training=None):
x, x_cond = inputs
x = self.spade_norm([x, x_cond], training=training)
if self.activation is not None:
x = self.activation(x)
x = self.conv(x, training=training)
return x
class SPADEResBlock(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, fin, fout, conv_layer, act_layer, pre_norm_layer,
projection_filters=128, spade_norm_conv_layer=None,
order=NHWC, **kwargs):
super(SPADEResBlock, self).__init__(**kwargs)
if spade_norm_conv_layer is None:
spade_norm_conv_layer = conv_layer
f_middle = min(fin, fout)
# x_shortcut = x_init
if fin != fout:
# Shortcut doesn't have activation after norm, its conv has no bias and
# its kernel_size is 1.
self.shortcut = SPADEConvBlock(
pre_norm_layer, None, conv_layer, fout, spade_norm_conv_layer,
projection_filters=projection_filters, kernel_size=1, use_bias=False,
name='spade_block_shortcut')
else:
self.shortcut = None
self.conv_block0 = SPADEConvBlock(
pre_norm_layer, act_layer, conv_layer, f_middle, spade_norm_conv_layer,
projection_filters=projection_filters, name='spade_block_conv0')
self.conv_block1 = SPADEConvBlock(
pre_norm_layer, act_layer, conv_layer, fout, spade_norm_conv_layer,
projection_filters=projection_filters, name='spade_block_conv1')
def call(self, inputs, training=None):
x, x_cond = inputs
if self.shortcut is not None:
x_shortcut = self.shortcut([x, x_cond], training=training)
else:
x_shortcut = x
x = self.conv_block0([x, x_cond], training=training)
x = self.conv_block1([x, x_cond], training=training)
return x + x_shortcut
class SPADENormalization(tf.keras.layers.Layer):
"""TBD."""
# NOTE: SPADE_norm uses 3x3 conv when using sync_batch_norm and 5x5 conv --
# when using instance_norm (but 5x5 seems a lot slower)!.
def __init__(self, pre_norm_layer, conv_layer, projection_filters=128,
kernel_size=3, order=NHWC, **kwargs):
super(SPADENormalization, self).__init__(**kwargs)
self.projection_filters = projection_filters
self.order = order
data_format = 'channels_last' if order == NHWC else 'channels_first'
self.conv_layer = functools.partial(
conv_layer, kernel_size=kernel_size, strides=1, padding='SAME',
use_bias=True, data_format=data_format)
self.pre_norm_layer = pre_norm_layer
def build(self, input_shape):
super(SPADENormalization, self).build(input_shape)
# Extract shapes and compute downscale factor for the spatial input.
x_shape, x_cond_shape = input_shape
_, x_h, x_w, x_nc = x_shape
_, x_cond_h, x_cond_w, _ = x_cond_shape
assert x_h == x_w and x_cond_h == x_cond_w # supports square resolutions
self.downscale_factor = x_cond_h // x_h
# Build conv layers.
# The first conv uses ReLU activation.
self.conv0 = self.conv_layer(
filters=self.projection_filters, activation=tf.nn.relu,
name='spade_projection_conv')
self.gamma_conv = self.conv_layer(filters=x_nc, activation=None,
name='gamma_conv')
self.beta_conv = self.conv_layer(filters=x_nc, activation=None,
name='beta_conv')
self.feature_mod = FeatureModulation(self.pre_norm_layer, self.order,
name='feature_mod')
def call(self, inputs, training=None):
x, x_cond = inputs
# QUES: does downscaled2d() create a new tensor with each call() execution?
x_cond_down = downscale2d(x_cond, n=self.downscale_factor, order=self.order)
x_cond_down = self.conv0(x_cond_down, training=training)
gamma_map = self.gamma_conv(x_cond_down, training=training)
beta_map = self.beta_conv(x_cond_down, training=training)
return self.feature_mod([x, gamma_map, beta_map], training=training)
class SelfAttention(tf.keras.layers.Layer):
"""Self-attention layer."""
def __init__(self, fout, conv_layer, channel_multiplier=1./8., pool_size=2,
order=NHWC, **kwargs):
assert order == NHWC, 'NCHW not yet supported (TBD).'
self.fout = fout
self.conv_layer = conv_layer
self.channel_multiplier = channel_multiplier
self.pool_size = pool_size
self.order = order
super(SelfAttention, self).__init__(**kwargs)
def build(self, input_shape):
batch_size, height, width, fin = input_shape
self.max_pool_layer = tf.keras.layers.MaxPool2D(
pool_size=self.pool_size, strides=2, padding='SAME')
num_inner_channels = max(int(self.channel_multiplier * self.fout), 1)
self.f_conv = self.conv_layer(
filters=num_inner_channels,
kernel_size=1,
strides=1,
use_bias=False,
activation=None,
name='f_conv') # [bs, h, w, c']
self.g_conv = self.conv_layer(
filters=num_inner_channels,
kernel_size=1,
strides=1,
use_bias=False,
activation=None,
name='g_conv') # [bs, h, w, c']
self.h_conv = self.conv_layer(
filters=num_inner_channels,
kernel_size=1,
strides=1,
use_bias=False,
activation=None,
name='h_conv') # [bs, h, w, c']
self.reshape_attention_output = functools.partial(
tf.reshape, shape=(batch_size, height, width, num_inner_channels))
self.attention_conv = self.conv_layer(
filters=fin,
kernel_size=1,
strides=1,
use_bias=False,
activation=None,
name='attention_conv') # [bs, h, w, c]
self.attention_weight = self.add_weight(
name='attention_weight',
shape=(),
dtype=self.dtype,
initializer=tf.constant_initializer(0.),
constraint=lambda x: tf.clip_by_value(x, 0, np.infty))
super(SelfAttention, self).build(input_shape)
def call(self, inputs, training=None):
x = inputs
# f branch.
f_x = self.f_conv(x, training=training) # [bs, h, w, c']
f_x = self.max_pool_layer(f_x)
flattened_f_x = flatten_spatial_dimensions(f_x)
# g branch (no max pooling).
g_x = self.g_conv(x, training=training) # [bs, h, w, c']
flattened_g_x = flatten_spatial_dimensions(g_x)
# h branch.
h_x = self.h_conv(x, training=training) # [bs, h, w, c']
h_x = self.max_pool_layer(h_x)
flattened_h_x = flatten_spatial_dimensions(h_x)
# Compute flattened attention map.
attention_map = tf.matmul(flattened_g_x, flattened_f_x,
transpose_b=True) # [bs, flat(h*w), flat(h*w)]
attention_map = tf.nn.softmax(attention_map, axis=-1)
# Weight the flattend h branch with the flattend attention map.
flattened_out = tf.matmul(
attention_map, flattened_h_x) # [bs, flat(h*w), c']
# Reshape the flattened weighted output back to 4D.
out = self.reshape_attention_output(flattened_out) # [bs, h, w, c']
# Apply final convolution and add a shortcut.
attention_conv_output = self.attention_conv(
out, training=training) # [bs, h, w, c]
x = self.attention_weight * attention_conv_output + x
return x
class DenseScaled(tf.keras.layers.Dense):
"""Learning rate scaled version of the tf.layers.Dense.
"""
def __init__(self, units, gain=1, lr_mul=1, **kwargs):
init_std = 1. / lr_mul
super(DenseScaled, self).__init__(
units=units,
kernel_initializer=tf.random_normal_initializer(stddev=init_std),
**kwargs)
self.gain = gain
self.lr_mul = lr_mul
def build(self, input_shape):
super(DenseScaled, self).build(input_shape)
he_scale = _kaiming_scale(self.kernel.shape.as_list())
self.runtime_coeff = tf.constant(self.gain * self.lr_mul * he_scale,
dtype=self.kernel.dtype)
def call(self, inputs):
# QUES: does tf.matmul() create a new tensor with each call() execution?
# outputs = tf.matmul(inputs, self.kernel * cur_scale)
outputs = gen_math_ops.mat_mul(inputs, self.kernel * self.runtime_coeff)
if self.use_bias:
outputs = nn.bias_add(outputs, self.bias)
if self.activation is None:
return outputs
return self.activation(outputs)
def set_gain(self, gain):
self.gain = gain
class Conv2DScaled(tf.keras.layers.Conv2D):
"""Learning rate scaled version of the tf.layers.Conv2D.
"""
def __init__(self, filters, padding='same', gain=1, lr_mul=1, **kwargs):
self.gain = gain
init_std = 1. / lr_mul
super(Conv2DScaled, self).__init__(
filters=filters,
padding=padding,
kernel_initializer=tf.random_normal_initializer(stddev=init_std),
**kwargs)
def build(self, input_shape):
super(Conv2DScaled, self).build(input_shape)
he_scale = _kaiming_scale(self.kernel.shape.as_list())
self.runtime_coeff = tf.constant(self.gain * he_scale,
dtype=self.kernel.dtype)
def call(self, inputs):
if self._recreate_conv_op(inputs):
self._convolution_op = nn_ops.Convolution(
inputs.get_shape(),
filter_shape=self.kernel.shape,
dilation_rate=self.dilation_rate,
strides=self.strides,
padding=self._padding_op,
data_format=self._conv_op_data_format)
outputs = self._convolution_op(inputs, self.kernel * self.runtime_coeff)
if self.use_bias:
fmt = 'NCHW' if self.data_format == 'channels_first' else 'NHWC'
outputs = nn.bias_add(outputs, self.bias, data_format=fmt)
if self.activation is not None:
return self.activation(outputs)
return outputs
def set_gain(self, gain):
self.gain = gain
class DenseScaled2(tf.keras.layers.Dense):
"""Learning rate scaled version of the tf.layers.Dense.
"""
def __init__(self, units, gain=1, lr_mul=1, **kwargs):
init_std = 1. / lr_mul
super(DenseScaled2, self).__init__(
units=units,
kernel_initializer=tf.random_normal_initializer(stddev=init_std),
**kwargs)
self.gain = gain
self.lr_mul = lr_mul
def build(self, input_shape):
super(DenseScaled2, self).build(input_shape)
he_scale = _kaiming_scale(self.kernel.shape.as_list())
self.runtime_coeff = self.gain * self.lr_mul * he_scale
def call(self, inputs):
output = super(DenseScaled2, self).call(inputs)
return self.runtime_coeff * output
class Conv2DScaled2(tf.keras.layers.Conv2D):
"""Learning rate scaled version of the tf.layers.Conv2D.
"""
def __init__(self, filters, gain=1, lr_mul=1, **kwargs):
self.gain = gain
self.lr_mul = lr_mul
init_std = 1. / lr_mul
super(Conv2DScaled2, self).__init__(
filters=filters,
kernel_initializer=tf.random_normal_initializer(stddev=init_std),
**kwargs)
def build(self, input_shape):
super(Conv2DScaled2, self).build(input_shape)
he_scale = _kaiming_scale(self.kernel.shape.as_list())
self.runtime_coeff = self.gain * self.lr_mul * he_scale
def call(self, inputs):
output = super(Conv2DScaled2, self).call(inputs)
return self.runtime_coeff * output
class ParamFreeInstanceNorm(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, epsilon=1e-8, order=NHWC, name=None, **kwargs):
self.reduce_axes = [1, 2] if order == NHWC else [2, 3]
self.eps = tf.constant(epsilon, name='epsilon')
super(ParamFreeInstanceNorm, self).__init__(name=name, **kwargs)
def call(self, x):
x -= tf.reduce_mean(x, axis=self.reduce_axes, keepdims=True)
x *= tf.math.rsqrt(
self.eps + tf.reduce_mean(
tf.math.square(x), axis=self.reduce_axes, keepdims=True))
return x
class FeatureModulation(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, pre_norm_layer, order=NHWC, name=None, **kwargs):
super(FeatureModulation, self).__init__(name=name, **kwargs)
self.norm_layer = pre_norm_layer()
self.order = order
def call(self, inputs, training=None):
x, gamma_map, beta_map = inputs
if self.norm_layer is not None:
x = self.norm_layer(x, training=training)
return x * (1 + gamma_map) + beta_map
class StyleModulation(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, dense_layer, param_free_norm=None, order=NHWC, **kwargs):
super(StyleModulation, self).__init__(**kwargs)
self.dense_layer = dense_layer
self.order = order
self.feature_mod = FeatureModulation(param_free_norm, order=order)
def build(self, input_shape): # Expects a pair of inputs (x, dlatents).
super(StyleModulation, self).build(input_shape)
x_shape, _ = input_shape
channel_dim = -1 if self.order == NHWC else 1
num_out_filters = 2 * x_shape[channel_dim]
self.dense = self.dense_layer(units=num_out_filters, use_bias=True,
name='dense')
if self.order == NHWC:
self.reshape = [-1, 2, 1, 1, x_shape[channel_dim]]
else:
self.reshape = [-1, 2, x_shape[channel_dim], 1, 1]
def call(self, inputs, training=None):
x, dlatents = inputs
gammas_and_betas = self.dense(dlatents, training=training)
gammas_and_betas = tf.reshape(gammas_and_betas, self.reshape)
gamma_map = gammas_and_betas[:, 0]
beta_map = gammas_and_betas[:, 1]
return self.feature_mod([x, gamma_map, beta_map], training=training)
class StyleGANSpatialNoise(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, per_channel_noise_weight=True, order=NHWC, **kwargs):
super(StyleGANSpatialNoise, self).__init__(**kwargs)
self.order = order
self.channel_dim = 3 if self.order == NHWC else 1
self.per_channel_noise_weight = per_channel_noise_weight
def build(self, input_shape):
super(StyleGANSpatialNoise, self).build(input_shape)
if self.per_channel_noise_weight:
weight_shape = [1, 1, 1, 1]
weight_shape[self.channel_dim] = input_shape[self.channel_dim]
else: # scalar weight for all channels as in StyleGAN2
weight_shape = []
self.noise_weight = self.add_weight(
name='noise_weight', shape=weight_shape,
initializer=tf.initializers.zeros(), trainable=True)
def call(self, x, noise_map=None):
if noise_map is None:
noise_shape = x.shape.as_list().copy()
noise_shape[self.channel_dim] = 1
noise_map = tf.random.normal(noise_shape, dtype=x.dtype)
else:
noise_map = tf.dtypes.cast(self.noise_map, x.dtype)
noise_weight = tf.dtypes.cast(self.noise_weight, x.dtype)
return x + noise_weight * noise_map
class BiasLayer(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, lr_mul=1, order=NHWC, **kwargs):
super(BiasLayer, self).__init__(**kwargs)
self.lr_mul = lr_mul
self.order = order
def build(self, input_shape):
super(BiasLayer, self).build(input_shape)
# The following works for both 2D and 4D tensors.
channel_dim = -1 if self.order == NHWC else 1
bias_shape = [1] * len(input_shape)
bias_shape[channel_dim] = input_shape[channel_dim]
self.bias = self.add_weight(
name='bias', shape=bias_shape, initializer=tf.initializers.zeros(),
trainable=True)
def call(self, inputs):
return inputs + tf.dtypes.cast(self.bias * self.lr_mul, inputs.dtype)
# NOTE: this isn't completely faithful to styleGAN's released code.
class StyleGANLayerEpilogue(tf.keras.layers.Layer):
"""TBD."""
def __init__(self, nf, conv_layer, dense_layer, act_layer, norm_layer,
add_spatial_noise=True, use_style_mod=True, order=NHWC,
**kwargs):
super(StyleGANLayerEpilogue, self).__init__(**kwargs)
self.add_spatial_noise = add_spatial_noise
self.use_style_mod = use_style_mod
if conv_layer is not None:
data_format = 'channels_last' if order == NHWC else 'channels_first'
self.conv = conv_layer(nf, kernel_size=1, strides=1, padding='SAME',
use_bias=False, activation=None,
data_format=data_format, name='conv2d')
else:
self.conv = None
if add_spatial_noise:
self.add_noise = StyleGANSpatialNoise(name='spatial_noise', order=order)
self.add_bias = BiasLayer(order=order, name='bias_add')
self.activation = act_layer()
if use_style_mod:
self.style_mod = StyleModulation(
dense_layer, param_free_norm=norm_layer, order=order,
name='style_mod')
else:
self.normalize = norm_layer()
def call(self, inputs, training=None): # Expects 2 inputs: {x, dlatents=None}
x, dlatents = inputs
if self.conv is not None:
x = self.conv(x, training=training)
if self.add_spatial_noise:
x = self.add_noise(x, training=training)
x = self.add_bias(x, training=training)
x = self.activation(x)
if self.use_style_mod:
x = self.style_mod([x, dlatents], training=training)
else:
x = self.normalize(x, training=training)
return x
class IdentityLayer(tf.keras.layers.Layer):
"""TBD."""
def call(self, inputs):
return inputs
# Copy of tensorflow 2.x InstanceNormalization code to use with tf 1.15.
# TODO: Need to replace with tf_addons implementation.
class InstanceNormalization(tf.keras.layers.Layer):
"""Instance normalization layer.
Normalize the activations of the previous layer at each step,
i.e. applies a transformation that maintains the mean activation
close to 0 and the activation standard deviation close to 1.
# Arguments
axis: Integer, the axis that should be normalized
(typically the features axis).
For instance, after a `Conv2D` layer with
`data_format="channels_first"`,
set `axis=1` in `InstanceNormalization`.
Setting `axis=None` will normalize all values in each
instance of the batch.
Axis 0 is the batch dimension. `axis` cannot be set to 0 to avoid errors.
epsilon: Small float added to variance to avoid dividing by zero.
center: If True, add offset of `beta` to normalized tensor.
If False, `beta` is ignored.
scale: If True, multiply by `gamma`.
If False, `gamma` is not used.
When the next layer is linear (also e.g. `nn.relu`),
this can be disabled since the scaling
will be done by the next layer.
beta_initializer: Initializer for the beta weight.
gamma_initializer: Initializer for the gamma weight.
beta_regularizer: Optional regularizer for the beta weight.
gamma_regularizer: Optional regularizer for the gamma weight.
beta_constraint: Optional constraint for the beta weight.
gamma_constraint: Optional constraint for the gamma weight.
# Input shape
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer in a Sequential model.
# Output shape
Same shape as input.
# References
- [Layer Normalization](https://arxiv.org/abs/1607.06450)
- [Instance Normalization: The Missing Ingredient for Fast Stylization](
https://arxiv.org/abs/1607.08022)
"""
def __init__(self,
axis=None,
epsilon=1e-3,
center=True,
scale=True,
beta_initializer='zeros',
gamma_initializer='ones',
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
**kwargs):
super(InstanceNormalization, self).__init__(**kwargs)
self.supports_masking = True
self.axis = axis
self.epsilon = epsilon
self.center = center
self.scale = scale
self.beta_initializer = tf.keras.initializers.get(beta_initializer)
self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)
self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)
self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)
self.beta_constraint = tf.keras.constraints.get(beta_constraint)
self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)
def build(self, input_shape):
ndim = len(input_shape)
if self.axis == 0:
raise ValueError('Axis cannot be zero')
if (self.axis is not None) and (ndim == 2):
raise ValueError('Cannot specify axis for rank 1 tensor')
self.input_spec = tf.keras.layers.InputSpec(ndim=ndim)
if self.axis is None:
shape = (1,)
else:
shape = (input_shape[self.axis],)
if self.scale:
self.gamma = self.add_weight(shape=shape,
name='gamma',
initializer=self.gamma_initializer,
regularizer=self.gamma_regularizer,
constraint=self.gamma_constraint)
else:
self.gamma = None
if self.center:
self.beta = self.add_weight(shape=shape,
name='beta',
initializer=self.beta_initializer,
regularizer=self.beta_regularizer,
constraint=self.beta_constraint)
else:
self.beta = None
self.built = True
def call(self, inputs, training=None):
input_shape = tf.keras.backend.int_shape(inputs)
reduction_axes = list(range(0, len(input_shape)))
if self.axis is not None:
del reduction_axes[self.axis]
del reduction_axes[0]
mean = tf.keras.backend.mean(inputs, reduction_axes, keepdims=True)
stddev = tf.keras.backend.std(
inputs, reduction_axes, keepdims=True) + self.epsilon
normed = (inputs - mean) / stddev
broadcast_shape = [1] * len(input_shape)
if self.axis is not None:
broadcast_shape[self.axis] = input_shape[self.axis]
if self.scale:
broadcast_gamma = tf.keras.backend.reshape(self.gamma, broadcast_shape)
normed = normed * broadcast_gamma
if self.center:
broadcast_beta = tf.keras.backend.reshape(self.beta, broadcast_shape)
normed = normed + broadcast_beta
return normed
def get_config(self):
config = {
'axis': self.axis,
'epsilon': self.epsilon,
'center': self.center,
'scale': self.scale,
'beta_initializer': tf.keras.initializers.serialize(
self.beta_initializer),
'gamma_initializer': tf.keras.initializers.serialize(
self.gamma_initializer),
'beta_regularizer': tf.keras.regularizers.serialize(
self.beta_regularizer),
'gamma_regularizer': tf.keras.regularizers.serialize(
self.gamma_regularizer),
'beta_constraint': tf.keras.constraints.serialize(self.beta_constraint),
'gamma_constraint': tf.keras.constraints.serialize(
self.gamma_constraint)
}
base_config = super(InstanceNormalization, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
# -----------------------------------------------------------------------------
# TODOs section: the following are not yet converted into the new API!
# -----------------------------------------------------------------------------
# TODO(meshry): wrap in a tf.keras.layers.Layer class.
def channel_norm(x, order=NHWC):
"""Channel normalization.
Args:
x: 4D image tensor (in either NCHW or NHWC format).
order: enum(NCHW, NHWC), the order of channels vs dimensions in the image
tensor.