This repository has been archived by the owner on Oct 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 238
/
layers.py
241 lines (201 loc) · 7.89 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
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Layer, InputSpec, DepthwiseConv2D
from tensorflow.keras.layers import Conv2D, BatchNormalization, Add
from tensorflow.keras.layers import ReLU, LeakyReLU, ZeroPadding2D
from keras_contrib.layers import InstanceNormalization
def channel_shuffle_2(x):
dyn_shape = tf.shape(x)
h, w = dyn_shape[1], dyn_shape[2]
c = x.shape[3]
x = K.reshape(x, [-1, h, w, 2, c // 2])
x = K.permute_dimensions(x, [0, 1, 2, 4, 3])
x = K.reshape(x, [-1, h, w, c])
return x
class ReflectionPadding2D(Layer):
def __init__(self, padding=(1, 1), **kwargs):
super(ReflectionPadding2D, self).__init__(**kwargs)
padding = tuple(padding)
self.padding = ((0, 0), padding, padding, (0, 0))
self.input_spec = [InputSpec(ndim=4)]
def compute_output_shape(self, s):
""" If you are using "channels_last" configuration"""
return s[0], s[1] + 2 * self.padding[0], s[2] + 2 * self.padding[1], s[3]
def call(self, x):
return tf.pad(x, self.padding, "REFLECT")
def get_padding(pad_type, padding):
if pad_type == "reflect":
return ReflectionPadding2D(padding)
elif pad_type == "constant":
return ZeroPadding2D(padding)
else:
raise ValueError(f"Unrecognized pad_type {pad_type}")
def get_norm(norm_type):
if norm_type == "instance":
return InstanceNormalization()
elif norm_type == 'batch':
return BatchNormalization()
else:
raise ValueError(f"Unrecognized norm_type {norm_type}")
class FlatConv(Model):
def __init__(self,
filters,
kernel_size,
norm_type="instance",
pad_type="constant",
**kwargs):
super(FlatConv, self).__init__(name="FlatConv")
padding = (kernel_size - 1) // 2
padding = (padding, padding)
self.model = tf.keras.models.Sequential()
self.model.add(get_padding(pad_type, padding))
self.model.add(Conv2D(filters, kernel_size))
self.model.add(get_norm(norm_type))
self.model.add(ReLU())
def build(self, input_shape):
super(FlatConv, self).build(input_shape)
def call(self, x, training=False):
return self.model(x, training=training)
class BasicShuffleUnitV2(Model):
def __init__(self,
filters, # NOTE: will be filters // 2
norm_type="instance",
pad_type="constant",
**kwargs):
super(BasicShuffleUnitV2, self).__init__(name="BasicShuffleUnitV2")
filters //= 2
self.model = tf.keras.models.Sequential([
Conv2D(filters, 1, use_bias=False),
get_norm(norm_type),
ReLU(),
DepthwiseConv2D(3, padding='same', use_bias=False),
get_norm(norm_type),
Conv2D(filters, 1, use_bias=False),
get_norm(norm_type),
ReLU(),
])
def build(self, input_shape):
super(BasicShuffleUnitV2, self).build(input_shape)
def call(self, x, training=False):
xl, xr = tf.split(x, 2, 3)
x = tf.concat((xl, self.model(xr)), 3)
return channel_shuffle_2(x)
class DownShuffleUnitV2(Model):
def __init__(self,
filters, # NOTE: will be filters // 2
norm_type="instance",
pad_type="constant",
**kwargs):
super(DownShuffleUnitV2, self).__init__(name="DownShuffleUnitV2")
filters //= 2
self.r_model = tf.keras.models.Sequential([
Conv2D(filters, 1, use_bias=False),
get_norm(norm_type),
ReLU(),
DepthwiseConv2D(3, 2, 'same', use_bias=False),
get_norm(norm_type),
Conv2D(filters, 1, use_bias=False),
])
self.l_model = tf.keras.models.Sequential([
DepthwiseConv2D(3, 2, 'same', use_bias=False),
get_norm(norm_type),
Conv2D(filters, 1, use_bias=False),
])
self.bn_act = tf.keras.models.Sequential([
get_norm(norm_type),
ReLU(),
])
def build(self, input_shape):
super(DownShuffleUnitV2, self).build(input_shape)
def call(self, x, training=False):
x = tf.concat((self.l_model(x), self.r_model(x)), 3)
x = self.bn_act(x)
return channel_shuffle_2(x)
class ConvBlock(Model):
def __init__(self,
filters,
kernel_size,
stride=1,
norm_type="instance",
pad_type="constant",
**kwargs):
super(ConvBlock, self).__init__(name="ConvBlock")
padding = (kernel_size - 1) // 2
padding = (padding, padding)
self.model = tf.keras.models.Sequential()
self.model.add(get_padding(pad_type, padding))
self.model.add(Conv2D(filters, kernel_size, stride))
self.model.add(get_padding(pad_type, padding))
self.model.add(Conv2D(filters, kernel_size))
self.model.add(get_norm(norm_type))
self.model.add(ReLU())
def build(self, input_shape):
super(ConvBlock, self).build(input_shape)
def call(self, x, training=False):
return self.model(x, training=training)
class ResBlock(Model):
def __init__(self,
filters,
kernel_size,
norm_type="instance",
pad_type="constant",
**kwargs):
super(ResBlock, self).__init__(name="ResBlock")
padding = (kernel_size - 1) // 2
padding = (padding, padding)
self.model = tf.keras.models.Sequential()
self.model.add(get_padding(pad_type, padding))
self.model.add(Conv2D(filters, kernel_size))
self.model.add(get_norm(norm_type))
self.model.add(ReLU())
self.model.add(get_padding(pad_type, padding))
self.model.add(Conv2D(filters, kernel_size))
self.model.add(get_norm(norm_type))
self.add = Add()
def build(self, input_shape):
super(ResBlock, self).build(input_shape)
def call(self, x, training=False):
return self.add([self.model(x, training=training), x])
class UpSampleConv(Model):
def __init__(self,
filters,
kernel_size,
norm_type="instance",
pad_type="constant",
light=False,
**kwargs):
super(UpSampleConv, self).__init__(name="UpSampleConv")
if light:
self.model = tf.keras.models.Sequential([
Conv2D(filters, 1),
BasicShuffleUnitV2(filters, norm_type, pad_type)
])
else:
self.model = ConvBlock(
filters, kernel_size, 1, norm_type, pad_type)
def build(self, input_shape):
super(UpSampleConv, self).build(input_shape)
def call(self, x, training=False):
x = tf.keras.backend.resize_images(x, 2, 2, "channels_last", 'bilinear')
return self.model(x, training=training)
class StridedConv(Model):
def __init__(self,
filters=64,
lrelu_alpha=0.2,
pad_type="constant",
norm_type="batch",
**kwargs):
super(StridedConv, self).__init__(name="StridedConv")
self.model = tf.keras.models.Sequential()
self.model.add(get_padding(pad_type, (1, 1)))
self.model.add(Conv2D(filters, 3, strides=(2, 2)))
self.model.add(LeakyReLU(lrelu_alpha))
self.model.add(get_padding(pad_type, (1, 1)))
self.model.add(Conv2D(filters * 2, 3))
self.model.add(get_norm(norm_type))
self.model.add(LeakyReLU(lrelu_alpha))
def build(self, input_shape):
super(StridedConv, self).build(input_shape)
def call(self, x, training=False):
return self.model(x, training=training)