-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayers.py
238 lines (184 loc) · 7.58 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
import tensorflow as tf
import sonnet as snt
import functools
from keras import layers
from sonnet.src.conv import ConvND
def downsample_avg_pool(x):
"""Utility function for downsampling by 2x2 average pooling."""
return layers.AveragePooling2D(2, 2, data_format='channels_last')(x)
def downsample_avg_pool3d(x):
"""Utility function for downsampling by 2x2 average pooling."""
return layers.AveragePooling3D(2, 2, data_format='channels_last')(x)
def upsample_nearest_neighbor(inputs, upsample_size):
"""Nearest neighbor upsampling.
Args:
inputs: inputs of size [b, h, w, c] where b is the batch size, h the height,
w the width, and c the number of channels.
upsample_size: upsample size S.
Returns:
outputs: nearest neighbor upsampled inputs of size [b, s * h, s * w, c].
"""
return tf.image.resize(inputs, [upsample_size*inputs.shape[1], upsample_size*inputs.shape[2]], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
class Conv2D(snt.Module):
"""2D convolution."""
def __init__(self, output_channels, kernel_size, stride=1, rate=1,
padding='SAME', use_bias=True):
"""Constructor."""
super().__init__(name=None)
self._output_channels = output_channels
self._kernel_size = kernel_size
self._stride = stride
self._rate = rate
self._padding = padding
self._initializer = snt.initializers.Orthogonal()
self._use_bias = use_bias
self._conv2D = snt.Conv2D(
output_channels=self._output_channels,
kernel_shape=self._kernel_size,
stride=self._stride,
rate=self._rate,
padding=self._padding,
with_bias=self._use_bias,
w_init=self._initializer,
b_init=None
)
def __call__(self, tensor):
# TO BE IMPLEMENTED
# One possible implementation is provided in the Sonnet library: snt.Conv2D.
return self._conv2D(tensor)
class SNConv2D(ConvND):
"""2D convolution with spectral normalisation."""
def __init__(self, output_channels, kernel_size, stride=1, rate=1,
padding='SAME', sn_eps=0.0001, use_bias=True):
"""Constructor."""
super().__init__(
num_spatial_dims=2,
output_channels=output_channels,
kernel_shape=kernel_size,
stride=stride,
rate=rate,
padding=padding,
with_bias=use_bias,
w_init=snt.initializers.Orthogonal(),
b_init=None,
data_format="NHWC",
name=None)
self._spectral_normalizer = SpectralNormalizer(epsilon=sn_eps)
def __call__(self, tensor, is_training=True):
self._initialize(tensor)
if self.padding_func:
tensor = tf.pad(tensor, self._padding)
normed_w = self._spectral_normalizer(self.w, is_training=is_training)
outputs = tf.nn.convolution(
tensor,
normed_w,
strides=self.stride,
padding=self.conv_padding,
dilations=self.rate,
data_format=self.data_format)
if self.with_bias:
outputs = tf.nn.bias_add(
outputs, self.b, data_format=self.data_format)
return outputs
class SNConv3D(ConvND):
"""2D convolution with spectral normalisation."""
def __init__(self, output_channels, kernel_size, stride=1, rate=1,
padding='SAME', sn_eps=0.0001, use_bias=True):
"""Constructor."""
super().__init__(
num_spatial_dims=3,
output_channels=output_channels,
kernel_shape=kernel_size,
stride=stride,
rate=rate,
padding=padding,
with_bias=use_bias,
w_init=snt.initializers.Orthogonal(),
b_init=None,
data_format="NDHWC",
name=None)
self._spectral_normalizer = SpectralNormalizer(epsilon=sn_eps)
def __call__(self, tensor, is_training=True):
self._initialize(tensor)
if self.padding_func:
tensor = tf.pad(tensor, self._padding)
normed_w = self._spectral_normalizer(self.w, is_training=is_training)
outputs = tf.nn.convolution(
tensor,
normed_w,
strides=self.stride,
padding=self.conv_padding,
dilations=self.rate,
data_format=self.data_format)
if self.with_bias:
outputs = tf.nn.bias_add(
outputs, self.b, data_format=self.data_format)
return outputs
class Linear(snt.Module):
"""Simple linear layer.
Linear map from [batch_size, input_size] -> [batch_size, output_size].
"""
def __init__(self, output_size):
"""Constructor."""
super().__init__(name=None)
self._output_size = output_size
self._linear = snt.Linear(output_size=output_size)
def __call__(self, tensor):
return self._linear(tensor)
class BatchNorm(snt.Module):
"""Batch normalization."""
def __init__(self, calc_sigma=True):
"""Constructor."""
super().__init__(name=None)
self._calc_sigma = calc_sigma
self._batch_norm = snt.BatchNorm(
create_scale=calc_sigma, create_offset=True)
def __call__(self, tensor, is_training=True):
return self._batch_norm(tensor, is_training=is_training)
class ApplyAlongAxis(snt.Module):
"""Layer for applying an operation on each element, along a specified axis."""
def __init__(self, operation, axis=0):
"""Constructor."""
super().__init__(name=None)
self._operation = operation
self._axis = axis
def __call__(self, *args):
"""Apply the operation to each element of args along the specified axis."""
split_inputs = [tf.unstack(arg, axis=self._axis) for arg in args]
res = [self._operation(x) for x in zip(*split_inputs)]
return tf.stack(res, axis=self._axis)
class ApplyAlongAxis2(snt.Module):
"""Layer for applying an operation on each element, along a specified axis."""
def __init__(self, operation, axis=0):
"""Constructor."""
super().__init__(name=None)
self._operation = operation
self._axis = axis
def __call__(self, inputs):
"""Apply the operation to each element of args along the specified axis."""
split_inputs = tf.unstack(inputs, axis=self._axis)
res = [self._operation(x) for x in split_inputs]
return tf.stack(res, axis=self._axis)
class SpectralNormalizer(snt.Module):
def __init__(self, epsilon=1e-12, name=None):
super().__init__(name=name)
self.l2_normalize = functools.partial(
tf.math.l2_normalize, epsilon=epsilon)
@snt.once
def _initialize(self, weights):
init = self.l2_normalize(snt.initializers.TruncatedNormal()(
shape=[1, weights.shape[-1]], dtype=weights.dtype))
# 'u' tracks our estimate of the first spectral vector for the given weight.
self.u = tf.Variable(init, name='u', trainable=False)
def __call__(self, weights, is_training=True):
self._initialize(weights)
if is_training:
# Do a power iteration and update u and weights.
weights_matrix = tf.reshape(weights, [-1, weights.shape[-1]])
v = self.l2_normalize(self.u @ tf.transpose(weights_matrix))
v_w = v @ weights_matrix
u = self.l2_normalize(v_w)
sigma = tf.stop_gradient(tf.reshape(v_w @ tf.transpose(u), []))
self.u.assign(u)
weights.assign(weights / sigma)
return weights