forked from pawni/BayesByHypernet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_layers.py
336 lines (262 loc) · 11.8 KB
/
base_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
from __future__ import absolute_import, print_function, division
import tensorflow as tf
import numpy as np
def outer(x, y):
return tf.matmul(tf.expand_dims(x, 1), tf.transpose(tf.expand_dims(y, 1)))
class Layer(object):
def __init__(self, *args, **kwargs):
self._build(*args, **kwargs)
def __call__(self, x, *args, **kwargs):
return self.call(x, *args, **kwargs)
def call(self, x, *args, **kwargs):
raise NotImplementedError('Not implemented in abstract class')
with tf.variable_scope('implict_hypernet') as vs:
hypernet_vs = vs
with tf.variable_scope('') as vs:
none_vs = vs
class BBHDiscriminator(object):
def __init__(self, input_dim=1, units=[20, 20]):
self.layers = []
with tf.variable_scope(none_vs):
with tf.variable_scope('implicit_discriminator'):
for unit in units:
layer = tf.layers.Dense(unit, activation=tf.nn.relu)
layer.build((None, input_dim))
self.layers.append(layer)
input_dim = unit
layer = tf.layers.Dense(1)
layer.build((None, input_dim))
self.layers.append(layer)
def __call__(self, x, *args, **kwargs):
for layer in self.layers:
x = layer(x)
return x
class BBHLayer(Layer):
share_noise = True
def _get_weight(self, name, size, units=[16, 32], use_bias=True,
noise_shape=1, num_samples=5, num_slices=1,
activation_func=lambda x: tf.maximum(0.1 * x, x)):
slice_size = size[-1]
assert slice_size % num_slices == 0
gen_size = slice_size // num_slices
cond = tf.eye(num_slices)
with tf.variable_scope(hypernet_vs):
with tf.variable_scope(name):
flat_size = np.prod(size[:-1]) * gen_size
if self.share_noise:
bbh_noise_col = tf.get_collection('bbh_noise')
if len(bbh_noise_col) == 1:
z = bbh_noise_col[0]
else:
z = tf.random_normal((num_samples, noise_shape))
tf.add_to_collection('bbh_noise', z)
else:
z = tf.random_normal((num_samples, noise_shape))
z = tf.stack([
tf.concat([
tf.tile(tf.expand_dims(z[s_dim], 0), [num_slices, 1]),
cond], 1) for s_dim in range(num_samples)])
# [noise,cond, ..]
for unit in units:
z = tf.layers.dense(inputs=z, units=unit, use_bias=use_bias)
z = activation_func(z)
z = tf.layers.dense(inputs=z, units=flat_size,
use_bias=use_bias)
w = tf.reshape(z, [num_samples, -1])
tf.add_to_collection('gen_weights', w)
tf.add_to_collection('weight_samples', w)
return tf.reshape(w, [num_samples, ] + list(size))
class BBHDynLayer(Layer):
share_noise = False
def _get_weight(self, name, size, units=[16, 32], use_bias=False,
noise_shape=1,
activation_func=lambda x: tf.maximum(0.1 * x, x)):
with tf.variable_scope(hypernet_vs):
with tf.variable_scope(name):
flat_size = np.prod(size)
if self.share_noise:
bbh_noise_col = tf.get_collection('bbh_noise')
if len(bbh_noise_col) == 1:
z = bbh_noise_col[0]
else:
z = tf.random_normal((1, 1))
tf.add_to_collection('bbh_noise', z)
else:
z = tf.random_normal((1, 1))
layers = []
for unit in units:
layers.append(tf.layers.Dense(activation=activation_func, units=unit, use_bias=use_bias))
layers.append(tf.layers.Dense(units=flat_size, use_bias=use_bias))
def weight(z, cond):
cond = tf.reshape(cond, (1, -1))
z = tf.concat([z, cond], 1)
for layer in layers:
z = layer(z)
tf.add_to_collection('gen_weights', z)
tf.add_to_collection('weight_samples', z)
return tf.reshape(z, size)
return lambda x: weight(z, x)
class BBBLayer(Layer):
share_noise = False
def _get_weight(self, name, size, init_var=-9, prior_scale=1.):
with tf.variable_scope(name):
loc = tf.get_variable(
'loc', size, tf.float32,
tf.variance_scaling_initializer())
log_scale_sq = tf.get_variable(
'log_scale_sq', size, tf.float32,
tf.truncated_normal_initializer(init_var, 0.05))
if self.share_noise:
bbb_noise_col = tf.get_collection('bbb_noise')
if len(bbb_noise_col) == 1:
z = bbb_noise_col[0]
else:
z = tf.random_normal((1, ))
tf.add_to_collection('bbb_noise', z)
else:
z = tf.random_normal(size)
w = z * tf.sqrt(tf.exp(log_scale_sq)) + loc
tf.add_to_collection('gen_weights', w)
weight_samples = tf.stack([
tf.random_normal(size) * tf.sqrt(tf.exp(log_scale_sq)) + loc
for _ in range(5)])
weight_samples = tf.reshape(weight_samples, [5, -1])
tf.add_to_collection('weight_samples', weight_samples)
# kl = -0.5 * tf.reduce_sum(1 + log_scale_sq - tf.square(loc)
# - tf.exp(log_scale_sq))
kl = -0.5 * tf.reduce_sum(
1. + log_scale_sq - 2. * tf.log(prior_scale)
- ((tf.exp(log_scale_sq) + tf.square(loc))
/ (tf.square(prior_scale)))
)
tf.add_to_collection('bbb_locs', loc)
tf.add_to_collection('bbb_log_scale_sq', log_scale_sq)
tf.add_to_collection('bbb_kl', kl)
tf.add_to_collection('kl_term', kl)
return w
class MaskedNVPFlow(object):
"""
copied from https://github.com/AMLab-Amsterdam/MNF_VBNN/
"""
def __init__(self, name, incoming, n_flows=2, n_hidden=0, dim_h=10,
scope=None, nonlin=tf.nn.tanh, **kwargs):
self.incoming = incoming
self.n_flows = n_flows
self.n_hidden = n_hidden
self.name = name
self.dim_h = dim_h
self.params = []
self.nonlin = nonlin
self.scope = scope
self.build()
def build_mnn(self, fid, param_list):
dimin = self.incoming
with tf.variable_scope(self.scope):
w = tf.get_variable(
'w{}_{}_{}'.format(0, self.name, fid),
(dimin, self.dim_h), tf.float32,
tf.variance_scaling_initializer())
b = tf.get_variable(
'b{}_{}_{}'.format(0, self.name, fid),
(self.dim_h, ), tf.float32,
tf.truncated_normal_initializer(0., 0.05))
param_list.append([(w, b)])
for l in range(self.n_hidden):
wh = tf.get_variable(
'w{}_{}_{}'.format(l + 1, self.name, fid),
(self.dim_h, self.dim_h), tf.float32,
tf.uniform_unit_scaling_initializer())
bh = tf.get_variable(
'b{}_{}_{}'.format(l + 1, self.name, fid),
(self.dim_h), tf.float32,
tf.zeros_initializer())
param_list[-1].append((wh, bh))
wout = tf.get_variable(
'w{}_{}_{}'.format(self.n_hidden + 1, self.name, fid),
(self.dim_h, dimin), tf.float32,
tf.variance_scaling_initializer())
bout = tf.get_variable(
'b{}_{}_{}'.format(self.n_hidden + 1, self.name, fid),
(dimin, ), tf.float32,
tf.zeros_initializer())
wout2 = tf.get_variable(
'w{}_{}_{}_sigma'.format(self.n_hidden + 1, self.name, fid),
(self.dim_h, dimin), tf.float32,
tf.variance_scaling_initializer())
bout2 = tf.get_variable(
'b{}_{}_{}_sigma'.format(self.n_hidden + 1, self.name, fid),
(dimin, ), tf.float32,
tf.constant_initializer(2.))
param_list[-1].append((wout, bout, wout2, bout2))
def build(self):
for flow in range(self.n_flows):
self.build_mnn('muf_{}'.format(flow), self.params)
def ff(self, x, weights):
inputs = [x]
for j in range(len(weights[:-1])):
h = tf.matmul(inputs[-1], weights[j][0]) + weights[j][1]
inputs.append(self.nonlin(h))
wmu, bmu, wsigma, bsigma = weights[-1]
mean = tf.matmul(inputs[-1], wmu) + bmu
sigma = tf.matmul(inputs[-1], wsigma) + bsigma
return mean, sigma
def random_bernoulli(self, shape, p=0.5):
if isinstance(shape, (list, tuple)):
shape = tf.stack(shape)
return tf.where(tf.random_uniform(shape) < p, tf.ones(shape),
tf.zeros(shape))
def get_output_for(self, z, sample=True):
logdets = tf.zeros((tf.shape(z)[0],))
for flow in range(self.n_flows):
mask = self.random_bernoulli(tf.shape(z), p=0.5) if sample else 0.5
ggmu, ggsigma = self.ff(mask * z, self.params[flow])
gate = tf.nn.sigmoid(ggsigma)
logdets += tf.reduce_sum((1 - mask) * tf.log(gate), axis=1)
z = (1 - mask) * (z * gate + (1 - gate) * ggmu) + mask * z
return z, logdets
class PlanarFlow(object):
"""
copied from https://github.com/AMLab-Amsterdam/MNF_VBNN/
"""
def __init__(self, name, incoming, n_flows=2, scope=None,
**kwargs):
self.incoming = incoming
self.n_flows = n_flows
self.sigma = 0.01
self.params = []
self.name = name
self.scope = scope
self.build()
def build(self):
with tf.variable_scope(self.scope):
for flow in range(self.n_flows):
w = tf.get_variable(
'w_{}_{}'.format(flow, self.name),
(self.incoming, 1), tf.float32,
tf.variance_scaling_initializer())
u = tf.get_variable(
'u_{}_{}'.format(flow, self.name),
(self.incoming, 1), tf.float32,
tf.truncated_normal_initializer(0., 0.05))
b = tf.get_variable(
'b_{}_{}'.format(flow, self.name),
(1, ), tf.float32,
tf.zeros_initializer())
self.params.append([w, u, b])
def get_output_for(self, z, **kwargs):
logdets = tf.zeros((tf.shape(z)[0],))
for flow in range(self.n_flows):
w, u, b = self.params[flow]
uw = tf.reduce_sum(u * w)
muw = -1 + tf.nn.softplus(uw) # = -1 + T.log(1 + T.exp(uw))
u_hat = u + (muw - uw) * w / tf.reduce_sum(w ** 2)
if len(z.get_shape()) == 1:
zwb = z * w + b
else:
zwb = tf.matmul(z, w) + b
psi = tf.matmul(1 - tf.nn.tanh(zwb) ** 2, tf.transpose(w)) # tanh(x)dx = 1 - tanh(x)**2
psi_u = tf.matmul(psi, u_hat)
logdets += tf.squeeze(tf.log(tf.abs(1 + psi_u)))
zadd = tf.matmul(tf.nn.tanh(zwb), tf.transpose(u_hat))
z += zadd
return z, logdets