-
Notifications
You must be signed in to change notification settings - Fork 6
/
log_likelihood_opt.py
369 lines (285 loc) · 13.5 KB
/
log_likelihood_opt.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import timeit
import collections
from monty.collections import AttrDict
import numpy as np
import sonnet as snt
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1 import nest
import tensorflow_probability as tfp
from stacked_capsule_autoencoders.capsules import math_ops
from stacked_capsule_autoencoders.capsules.neural import BatchMLP
tfd = tfp.distributions
"""Permutation-invariant capsule layer useed in constellation experiments."""
OutputTuple = collections.namedtuple('CapsuleLikelihoodTuple', # pylint:disable=invalid-name
('log_prob vote_presence winner '
'winner_pres is_from_capsule '
'mixing_logits mixing_log_prob '
'soft_winner soft_winner_pres '
'posterior_mixing_probs'))
# self._capsule_kwargs {'n_caps_params': 32, 'n_hiddens': 128,
# 'learn_vote_scale': True, 'deformations': True, 'noise_type': 'uniform',
# 'noise_scale': 4, 'similarity_transform': True}
#
# CAPSULE PARAMETERS
#
_n_caps = 3
_n_votes = 4
_n_caps_dims = 2
#
# CAPSULE DECODINGS RES. (log likelihood parameterization)
#
# Vote (result of decoding and transformed)
# key: vote, value: Tensor("constellation_autoencoder/constellation_capsule/strided_slice:0", shape=(32, 3, 4, 2), dtype=float32)
_votes = tf.random.uniform((32, 12, 2))
# Scale ~ std. dev
# key: scale, value: Tensor("constellation_autoencoder/constellation_capsule/capsule_layer/add_14:0", shape=(32, 3, 4), dtype=float32)
_scales = tf.random.uniform((32, 12))
# (conditional) vote probability
# key: vote_presence, value: Tensor("constellation_autoencoder/constellation_capsule/capsule_layer/mul_18:0", shape=(32, 3, 4), dtype=float32)
_vote_presence_prob = tf.random.uniform((32, 12))
def _get_pdf(votes, scale):
return tfd.Normal(votes, scale)
# Inputs
# *x* shape=(32, 11, 2), dtype=float32)
# *presence* shape=(32, 11), dtype=float32)
def naive_log_likelihood(x, presence=None):
"""Implementation from original repo ripped wholesale"""
batch_size, n_input_points = x.shape[:2].as_list()
# Generate gaussian mixture pdfs...
# [B, 1, n_votes, n_input_dims]
expanded_votes = tf.expand_dims(_votes, 1)
expanded_scale = tf.expand_dims(tf.expand_dims(_scales, 1), -1)
vote_component_pdf = _get_pdf(expanded_votes, expanded_scale)
# For each part, evaluates all capsule, vote mixture likelihoods
# [B, n_points, n_caps x n_votes, n_input_dims]
expanded_x = tf.expand_dims(x, 2)
vote_log_prob_per_dim = vote_component_pdf.log_prob(expanded_x)
# Compressing mixture likelihood across all part dimension (ie. 2d point)
# [B, n_points, n_caps x n_votes]
vote_log_prob = tf.reduce_sum(vote_log_prob_per_dim, -1)
dummy_vote_log_prob = tf.zeros([batch_size, n_input_points, 1])
dummy_vote_log_prob -= 2. * tf.log(10.)
# adding extra [B, n_points, n_caps x n_votes] to end. WHY?
vote_log_prob = tf.concat([vote_log_prob, dummy_vote_log_prob], 2)
# [B, n_points, n_caps x n_votes]
# CONDITIONAL LOGIT a_(k,n)
mixing_logits = math_ops.safe_log(_vote_presence_prob)
dummy_logit = tf.zeros([batch_size, 1]) - 2. * tf.log(10.)
mixing_logits = tf.concat([mixing_logits, dummy_logit], 1)
#
# Following seems relevant only towards compressing ll for loss.
# REDUNDANCY
#
# mixing_logits -> presence (a)
# vote_log_prob -> Gaussian value (one per vote) for each coordinate
# BAD -> vote presence / summed vote presence
mixing_log_prob = mixing_logits - tf.reduce_logsumexp(mixing_logits, 1,
keepdims=True)
# BAD -> mixing presence (above) * each vote gaussian prob
expanded_mixing_logits = tf.expand_dims(mixing_log_prob, 1)
# Reduce to loglikelihood given k,n combination (capsule, vote)
mixture_log_prob_per_component\
= tf.reduce_logsumexp(expanded_mixing_logits + vote_log_prob, 2)
if presence is not None:
presence = tf.to_float(presence)
mixture_log_prob_per_component *= presence
# Reduce votes to single capsule
# ^ Misleading, reducing across all parts, multiplying log
# likelihoods for each part _wrt all capsules_.
mixture_log_prob_per_example\
= tf.reduce_sum(mixture_log_prob_per_component, 1)
# Same as above but across all compressed part likelihoods in a batch.
mixture_log_prob_per_batch = tf.reduce_mean(
mixture_log_prob_per_example)
#
# Back from compression to argmax (routing to proper k)
#
# [B, n_points, n_votes]
posterior_mixing_logits_per_point = expanded_mixing_logits + vote_log_prob
# [B, n_points]
winning_vote_idx = tf.argmax(
posterior_mixing_logits_per_point[:, :, :-1], 2)
batch_idx = tf.expand_dims(tf.range(batch_size, dtype=tf.int64), -1)
batch_idx = snt.TileByDim([1], [winning_vote_idx.shape[-1]])(batch_idx)
idx = tf.stack([batch_idx, winning_vote_idx], -1)
winning_vote = tf.gather_nd(_votes, idx)
winning_pres = tf.gather_nd(_vote_presence_prob, idx)
vote_presence = tf.greater(mixing_logits[:, :-1],
mixing_logits[:, -1:])
# the first four votes belong to the square
# Just assuming the votes are ordered by capsule...
is_from_capsule = winning_vote_idx // _n_votes
posterior_mixing_probs = tf.nn.softmax(
posterior_mixing_logits_per_point, -1)[Ellipsis, :-1]
assert winning_vote.shape == x.shape
return OutputTuple(
log_prob=mixture_log_prob_per_batch,
vote_presence=tf.to_float(vote_presence),
winner=winning_vote,
winner_pres=winning_pres,
is_from_capsule=is_from_capsule,
mixing_logits=mixing_logits,
mixing_log_prob=mixing_log_prob,
# TODO(adamrk): this is broken
soft_winner=tf.zeros_like(winning_vote),
soft_winner_pres=tf.zeros_like(winning_pres),
posterior_mixing_probs=posterior_mixing_probs,
)
def argmax_log_likelihood(x, presence=None):
"""Most simple of the optimization schemes.
Skip the product of closeform probability of part given _all_ data. Rather
use the value at the argmax as a proxy for each part.
"""
batch_size, n_input_points = x.shape[:2].as_list()
# Generate gaussian mixture pdfs...
# [B, 1, n_votes, n_input_dims]
expanded_votes = tf.expand_dims(_votes, 1)
expanded_scale = tf.expand_dims(tf.expand_dims(_scales, 1), -1)
vote_component_pdf = _get_pdf(expanded_votes, expanded_scale)
# For each part, evaluates all capsule, vote mixture likelihoods
# [B, n_points, n_caps x n_votes, n_input_dims]
expanded_x = tf.expand_dims(x, 2)
vote_log_prob_per_dim = vote_component_pdf.log_prob(expanded_x)
# Compressing mixture likelihood across all part dimension (ie. 2d point)
# [B, n_points, n_caps x n_votes]
vote_log_prob = tf.reduce_sum(vote_log_prob_per_dim, -1)
dummy_vote_log_prob = tf.zeros([batch_size, n_input_points, 1])
dummy_vote_log_prob -= 2. * tf.log(10.)
# adding extra [B, n_points, n_caps x n_votes] to end. WHY?
vote_log_prob = tf.concat([vote_log_prob, dummy_vote_log_prob], 2)
# [B, n_points, n_caps x n_votes]
# CONDITIONAL LOGIT a_(k,n)
mixing_logits = math_ops.safe_log(_vote_presence_prob)
dummy_logit = tf.zeros([batch_size, 1]) - 2. * tf.log(10.)
mixing_logits = tf.concat([mixing_logits, dummy_logit], 1)
# BAD -> vote presence / summed vote presence
mixing_log_prob = mixing_logits - tf.reduce_logsumexp(mixing_logits, 1,
keepdims=True)
expanded_mixing_logits = tf.expand_dims(mixing_log_prob, 1)
# [B, n_points, n_votes]
posterior_mixing_logits_per_point = expanded_mixing_logits + vote_log_prob
# [B, n_points]
winning_vote_idx = tf.argmax(
posterior_mixing_logits_per_point[:, :, :-1], 2)
batch_idx = tf.expand_dims(tf.range(batch_size, dtype=tf.int64), -1)
batch_idx = snt.TileByDim([1], [winning_vote_idx.shape[-1]])(batch_idx)
idx = tf.stack([batch_idx, winning_vote_idx], -1)
winning_vote = tf.gather_nd(_votes, idx)
winning_pres = tf.gather_nd(_vote_presence_prob, idx)
vote_presence = tf.greater(mixing_logits[:, :-1],
mixing_logits[:, -1:])
# the first four votes belong to the square
# Just assuming the votes are ordered by capsule...
is_from_capsule = winning_vote_idx // _n_votes
posterior_mixing_probs = tf.nn.softmax(
posterior_mixing_logits_per_point, -1)[Ellipsis, :-1]
assert winning_vote.shape == x.shape
# log_prob=mixture_log_prob_per_batch,
return OutputTuple(
log_prob=None,
vote_presence=tf.to_float(vote_presence),
winner=winning_vote,
winner_pres=winning_pres,
is_from_capsule=is_from_capsule,
mixing_logits=mixing_logits,
mixing_log_prob=mixing_log_prob,
# TODO(adamrk): this is broken
soft_winner=tf.zeros_like(winning_vote),
soft_winner_pres=tf.zeros_like(winning_pres),
posterior_mixing_probs=posterior_mixing_probs,
)
def naive_mcmc_ll(x, presence=None):
"""Most simple of the optimization schemes.
Skip the product of closeform probability of part given _all_ data. Rather
use the value at the argmax as a proxy for each part.
"""
batch_size, n_input_points = x.shape[:2].as_list()
# Generate gaussian mixture pdfs...
# [B, 1, n_votes, n_input_dims]
expanded_votes = tf.expand_dims(_votes, 1)
expanded_scale = tf.expand_dims(tf.expand_dims(_scales, 1), -1)
vote_component_pdf = _get_pdf(expanded_votes, expanded_scale)
print("vote_component_pdf: ", vote_component_pdf)
# For each part, evaluates all capsule, vote mixture likelihoods
# [B, n_points, n_caps x n_votes, n_input_dims]
expanded_x = tf.expand_dims(x, 2)
print("expanded_x: ", expanded_x.shape)
vote_log_prob_per_dim = vote_component_pdf.log_prob(expanded_x)
print("vote_log_prob_dim: ", vote_log_prob_per_dim.shape)
# Compressing mixture likelihood across all part dimension (ie. 2d point)
# [B, n_points, n_caps x n_votes]
vote_log_prob = tf.reduce_sum(vote_log_prob_per_dim, -1)
print("vote_log_prob: ", vote_log_prob.shape)
dummy_vote_log_prob = tf.zeros([batch_size, n_input_points, 1])
dummy_vote_log_prob -= 2. * tf.log(10.)
print("dummy_vote: ", dummy_vote_log_prob.shape)
# adding extra [B, n_points, n_caps x n_votes] to end. WHY?
vote_log_prob = tf.concat([vote_log_prob, dummy_vote_log_prob], 2)
print("cat vote_log_prob: ", vote_log_prob.shape)
# [B, n_points, n_caps x n_votes]
# CONDITIONAL LOGIT a_(k,n)
mixing_logits = math_ops.safe_log(_vote_presence_prob)
dummy_logit = tf.zeros([batch_size, 1]) - 2. * tf.log(10.)
mixing_logits = tf.concat([mixing_logits, dummy_logit], 1)
print("mixing_logits : ", mixing_logits.shape)
# BAD -> vote presence / summed vote presence
mixing_log_prob = mixing_logits - tf.reduce_logsumexp(mixing_logits, 1,
keepdims=True)
print("mixing_log_prob : ", mixing_log_prob.shape)
expanded_mixing_logits = tf.expand_dims(mixing_log_prob, 1)
# [B, n_points, n_votes]
posterior_mixing_logits_per_point = expanded_mixing_logits + vote_log_prob
print("posterior_mixing_per_point: ",
posterior_mixing_logits_per_point.shape)
# [B, n_points]
winning_vote_idx = tf.argmax(
posterior_mixing_logits_per_point[:, :, :-1], 2)
print("winning_vote_idx: ",
winning_vote_idx.shape)
batch_idx = tf.expand_dims(tf.range(batch_size, dtype=tf.int64), -1)
batch_idx = snt.TileByDim([1], [winning_vote_idx.shape[-1]])(batch_idx)
idx = tf.stack([batch_idx, winning_vote_idx], -1)
winning_vote = tf.gather_nd(_votes, idx)
print("winning_vote: ", winning_vote.shape)
winning_pres = tf.gather_nd(_vote_presence_prob, idx)
print("winning_pres: ", winning_pres.shape)
vote_presence = tf.greater(mixing_logits[:, :-1],
mixing_logits[:, -1:])
print("vote_presence: ", vote_presence.shape)
# the first four votes belong to the square
# Just assuming the votes are ordered by capsule...
is_from_capsule = winning_vote_idx // _n_votes
print("is_from_capsule: ", is_from_capsule.shape)
posterior_mixing_probs = tf.nn.softmax(
posterior_mixing_logits_per_point, -1)[Ellipsis, :-1]
assert winning_vote.shape == x.shape
# log_prob=mixture_log_prob_per_batch,
return OutputTuple(
log_prob=None,
vote_presence=tf.to_float(vote_presence),
winner=winning_vote,
winner_pres=winning_pres,
is_from_capsule=is_from_capsule,
mixing_logits=mixing_logits,
mixing_log_prob=mixing_log_prob,
# TODO(adamrk): this is broken
soft_winner=tf.zeros_like(winning_vote),
soft_winner_pres=tf.zeros_like(winning_pres),
posterior_mixing_probs=posterior_mixing_probs,
)
#
# CAPSULE ENCODING RES. (log likelihood input)
#
# parts / points
# x Tensor("IteratorGetNext:0", shape=(32, 11, 2), dtype=float32)
x = tf.random.uniform((32, 11, 2))
# object probability
# presence Tensor("IteratorGetNext:3", shape=(32, 11), dtype=float32)
presence = tf.random.uniform((32, 11))
print(timeit.timeit(lambda: naive_log_likelihood(x, presence), number=100) /
100)
print(timeit.timeit(lambda: argmax_log_likelihood(x, presence), number=100) /
100)