-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathlayers.py
More file actions
368 lines (359 loc) · 16.4 KB
/
layers.py
File metadata and controls
368 lines (359 loc) · 16.4 KB
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
import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib.framework import add_arg_scope
@add_arg_scope
def double_conv2d(ref_half, real_half,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=None,
rate=1,
activation_fn=tf.nn.relu,
normalizer_fn=None,
normalize_after_activation=True,
normalizer_params=None,
weights_initializer=layers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=tf.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
with tf.variable_scope(scope, 'Conv', reuse=reuse):
if data_format == 'NHWC':
num_inputs = real_half.get_shape().as_list()[3]
height = real_half.get_shape().as_list()[1]
width = real_half.get_shape().as_list()[2]
if isinstance(stride, int):
strides = [1, stride, stride, 1]
elif isinstance(stride, list) or isinstance(stride, tuple):
if len(stride) == 1:
strides = [1] + stride * 2 + [1]
else:
strides = [1, stride[0], stride[1], 1]
else:
raise TypeError('stride is not an int, list or' \
+ 'a tuple, is %s' % type(stride))
else:
num_inputs = real_half.get_shape().as_list()[1]
height = real_half.get_shape().as_list()[2]
width = real_half.get_shape().as_list()[3]
if isinstance(stride, int):
strides = [1, 1, stride, stride]
elif isinstance(stride, list) or isinstance(stride, tuple):
if len(stride) == 1:
strides = [1, 1] + stride * 2
else:
strides = [1, 1, stride[0], stride[1]]
else:
raise TypeError('stride is not an int, list or' \
+ 'a tuple, is %s' % type(stride))
if isinstance(kernel_size, int):
kernel_height = kernel_size
kernel_width = kernel_size
elif isinstance(kernel_size, list) \
or isinstance(kernel_size, tuple):
kernel_height = kernel_size[0]
kernel_width = kernel_size[1]
else:
raise ValueError('kernel_size is not an int, list or' \
+ 'a tuple, is %s' % type(kernel_size))
weights = tf.get_variable('weights', [kernel_height, \
kernel_width, num_inputs, num_outputs], \
'float32', weights_initializer, \
weights_regularizer, trainable, \
variables_collections)
ref_outputs = tf.nn.conv2d(ref_half, weights, strides, padding, \
data_format=data_format)
real_outputs = tf.nn.conv2d(real_half, weights, strides, padding, \
data_format=data_format)
if biases_initializer is not None:
biases = tf.get_variable('biases', [num_outputs], 'float32', \
biases_initializer, \
biases_regularizer, \
trainable, variables_collections)
ref_outputs = tf.nn.bias_add(ref_outputs, biases, data_format)
real_outputs = tf.nn.bias_add(real_outputs, biases, data_format)
if normalizer_fn is not None \
and not normalize_after_activation:
normalizer_params = normalizer_params or {}
ref_outputs, real_outputs = normalizer_fn(ref_outputs, \
real_outputs, \
**normalizer_params)
if activation_fn is not None:
ref_outputs = activation_fn(ref_outputs)
real_outputs = activation_fn(real_outputs)
if normalizer_fn is not None and normalize_after_activation:
normalizer_params = normalizer_params or {}
ref_outputs, real_outputs = normalizer_fn(ref_outputs, \
real_outputs,\
**normalizer_params)
return ref_outputs, real_outputs
@add_arg_scope
def conv2d(inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=None,
rate=1,
activation_fn=tf.nn.relu,
normalizer_fn=None,
normalize_after_activation=True,
normalizer_params=None,
weights_initializer=layers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=tf.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
with tf.variable_scope(scope, 'Conv', reuse=reuse):
if data_format == 'NHWC':
num_inputs = inputs.get_shape().as_list()[3]
height = inputs.get_shape().as_list()[1]
width = inputs.get_shape().as_list()[2]
if isinstance(stride, int):
strides = [1, stride, stride, 1]
elif isinstance(stride, list) or isinstance(stride, tuple):
if len(stride) == 1:
strides = [1] + stride * 2 + [1]
else:
strides = [1, stride[0], stride[1], 1]
else:
raise TypeError('stride is not an int, list or' \
+ 'a tuple, is %s' % type(stride))
else:
num_inputs = inputs.get_shape().as_list()[1]
height = inputs.get_shape().as_list()[2]
width = inputs.get_shape().as_list()[3]
if isinstance(stride, int):
strides = [1, 1, stride, stride]
elif isinstance(stride, list) or isinstance(stride, tuple):
if len(stride) == 1:
strides = [1, 1] + stride * 2
else:
strides = [1, 1, stride[0], stride[1]]
else:
raise TypeError('stride is not an int, list or' \
+ 'a tuple, is %s' % type(stride))
if isinstance(kernel_size, int):
kernel_height = kernel_size
kernel_width = kernel_size
elif isinstance(kernel_size, list) \
or isinstance(kernel_size, tuple):
kernel_height = kernel_size[0]
kernel_width = kernel_size[1]
else:
raise ValueError('kernel_size is not an int, list or' \
+ 'a tuple, is %s' % type(kernel_size))
weights = tf.get_variable('weights', [kernel_height, \
kernel_width, num_inputs, num_outputs], \
'float32', weights_initializer, \
weights_regularizer, trainable, \
variables_collections)
outputs = tf.nn.conv2d(inputs, weights, strides, padding, \
data_format=data_format)
if biases_initializer is not None:
biases = tf.get_variable('biases', [num_outputs], 'float32', \
biases_initializer, \
biases_regularizer, \
trainable, variables_collections)
outputs = tf.nn.bias_add(outputs, biases, data_format)
if normalizer_fn is not None \
and not normalize_after_activation:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
if normalizer_fn is not None and normalize_after_activation:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
return outputs
class Vbn_double(object):
def __init__(self, x, epsilon=1e-5, scope=None):
shape = x.get_shape().as_list()
needs_reshape = len(shape) != 4
if needs_reshape:
orig_shape = shape
if len(shape) == 2:
if data_format == 'NCHW':
x = tf.reshape(x, [shape[0], shape[1], 0, 0])
else:
x = tf.reshape(x, [shape[0], 1, 1, shape[1]])
elif len(shape) == 1:
x = tf.reshape(x, [shape[0], 1, 1, 1])
else:
assert False, shape
shape = x.get_shape().as_list()
with tf.variable_scope(scope):
self.epsilon = epsilon
self.scope = scope
self.mean, self.var = tf.nn.moments(x, [0,2,3], \
keep_dims=True)
self.inv_std = tf.rsqrt(self.var + epsilon)
self.batch_size = int(x.get_shape()[0])
out = self._normalize(x, self.mean, self.inv_std)
if needs_reshape:
out = tf.reshape(out, orig_shape)
self.reference_output = out
def __call__(self, x):
shape = x.get_shape().as_list()
needs_reshape = len(shape) != 4
if needs_reshape:
orig_shape = shape
if len(shape) == 2:
if self.data_format == 'NCHW':
x = tf.reshape(x, [shape[0], shape[1], 0, 0])
else:
x = tf.reshape(x, [shape[0], 1, 1, shape[1]])
elif len(shape) == 1:
x = tf.reshape(x, [shape[0], 1, 1, 1])
else:
assert False, shape
with tf.variable_scope(self.scope, reuse=True):
out = self._normalize(x, self.mean, self.inv_std)
if needs_reshape:
out = tf.reshape(out, orig_shape)
return out
def _normalize(self, x, mean, inv_std):
shape = x.get_shape().as_list()
assert len(shape) == 4
gamma = tf.get_variable("gamma", [1,shape[1],1,1],
initializer=tf.constant_initializer(1.))
beta = tf.get_variable("beta", [1,shape[1],1,1],
initializer=tf.constant_initializer(0.))
coeff = gamma * inv_std
return (x * coeff) + (beta - mean * coeff)
@add_arg_scope
def vbn_double(ref_half, real_half, center=True, scale=True, epsilon=1e-5, \
data_format='NCHW', instance_norm=True, scope=None, \
reuse=None):
assert isinstance(epsilon, float)
shape = real_half.get_shape().as_list()
batch_size = int(real_half.get_shape()[0])
with tf.variable_scope(scope, 'VBN', reuse=reuse):
if data_format == 'NCHW':
if scale:
gamma = tf.get_variable("gamma", [1,shape[1],1,1],
initializer=tf.constant_initializer(1.))
if center:
beta = tf.get_variable("beta", [1,shape[1],1,1],
initializer=tf.constant_initializer(0.))
ref_mean, ref_var = tf.nn.moments(ref_half, [0,2,3], \
keep_dims=True)
else:
if scale:
gamma = tf.get_variable("gamma", [1,1,1,shape[-1]],
initializer=tf.constant_initializer(1.))
if center:
beta = tf.get_variable("beta", [1,1,1,shape[-1]],
initializer=tf.constant_initializer(0.))
ref_mean, ref_var = tf.nn.moments(ref_half, [0,1,2], \
keep_dims=True)
def _normalize(x, mean, var):
inv_std = tf.rsqrt(var + epsilon)
if scale:
coeff = inv_std * gamma
else:
coeff = inv_std
if center:
return (x * coeff) + (beta - mean * coeff)
else:
return (x - mean) * coeff
if instance_norm:
if data_format == 'NCHW':
real_mean, real_var = tf.nn.moments(real_half, [2,3], \
keep_dims=True)
else:
real_mean, real_var = tf.nn.moments(real_half, [1,2], \
keep_dims=True)
real_coeff = 1. / (batch_size + 1.)
ref_coeff = 1. - real_coeff
new_mean = real_coeff * real_mean + ref_coeff * ref_mean
new_var = real_coeff * real_var + ref_coeff * ref_var
ref_output = _normalize(ref_half, ref_mean, ref_var)
real_output = _normalize(real_half, new_mean, new_var)
else:
ref_output = _normalize(ref_half, ref_mean, ref_var)
real_output = _normalize(real_half, ref_mean, ref_var)
return ref_output, real_output
@add_arg_scope
def vbn_single(x, center=True, scale=True, \
epsilon=1e-5, data_format='NCHW', \
instance_norm=True, scope=None, \
reuse=None):
assert isinstance(epsilon, float)
shape = x.get_shape().as_list()
if shape[0] is None:
half_size = x.shape[0] // 2
else:
half_size = shape[0] // 2
needs_reshape = len(shape) != 4
if needs_reshape:
orig_shape = shape
if len(shape) == 2:
if data_format == 'NCHW':
x = tf.reshape(x, [shape[0], shape[1], 0, 0])
else:
x = tf.reshape(x, [shape[0], 1, 1, shape[1]])
elif len(shape) == 1:
x = tf.reshape(x, [shape[0], 1, 1, 1])
else:
assert False, shape
shape = x.get_shape().as_list()
batch_size = int(x.get_shape()[0])
with tf.variable_scope(scope, 'VBN', reuse=reuse):
ref_half = tf.slice(x, [0,0,0,0], [half_size, shape[1], \
shape[2], shape[3]])
if data_format == 'NCHW':
if scale:
gamma = tf.get_variable("gamma", [1,shape[1],1,1],
initializer=tf.constant_initializer(1.))
if center:
beta = tf.get_variable("beta", [1,shape[1],1,1],
initializer=tf.constant_initializer(0.))
ref_mean, ref_var = tf.nn.moments(ref_half, [0,2,3], \
keep_dims=True)
else:
if scale:
gamma = tf.get_variable("gamma", [1,1,1,shape[-1]],
initializer=tf.constant_initializer(1.))
if center:
beta = tf.get_variable("beta", [1,1,1,shape[-1]],
initializer=tf.constant_initializer(0.))
ref_mean, ref_var = tf.nn.moments(ref_half, [0,1,2], \
keep_dims=True)
def _normalize(x, mean, var):
inv_std = tf.rsqrt(var + epsilon)
if scale:
coeff = inv_std * gamma
else:
coeff = inv_std
if center:
return (x * coeff) + (beta - mean * coeff)
else:
return (x - mean) * coeff
if instance_norm:
real_half = tf.slice(x, [half_size,0,0,0], \
[half_size, shape[1], shape[2], shape[3]])
if data_format == 'NCHW':
real_mean, real_var = tf.nn.moments(real_half, [2,3], \
keep_dims=True)
else:
real_mean, real_var = tf.nn.moments(real_half, [1,2], \
keep_dims=True)
real_coeff = 1. / (batch_size + 1.)
ref_coeff = 1. - real_coeff
new_mean = real_coeff * real_mean + ref_coeff * ref_mean
new_var = real_coeff * real_var + ref_coeff * ref_var
ref_output = _normalize(ref_half, ref_mean, ref_var)
real_output = _normalize(real_half, new_mean, new_var)
return tf.concat([ref_output, real_output], axis=0)
else:
return _normalize(x, ref_mean, ref_var)