-
Notifications
You must be signed in to change notification settings - Fork 0
/
tensornets.py
1553 lines (1340 loc) · 66.3 KB
/
tensornets.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import tensorflow as tf
import pickle
from relaxflow.reparam import CategoricalReparam, categorical_forward, categorical_backward
dtype = 'float64'
epsilon = 1e-8
from tfutils import tffunc, tfmethod, HouseholderChain
select_max = lambda z, K: tf.one_hot(tf.argmax(z, axis=-1), K, dtype=dtype)
bitify = lambda x, K: np.sum(K**np.arange(len(x))*x)
def mosaic(Z, split=None):
'''matrix unfolding of tensor with even order with interpretable
row/column ordering.
Specifically, if it has order N, with each order having dimension K, we
can associate every element with an index of length N taking values in
{0,...,K-1}. Mosaic splits the index set into two vectors of N/2, one with
the odd indices and the other with the even. Both vectors are then encoded
as a base-K number. Each tensor element is then mapped to a row-column
index in the output matrix based on the base-K codes.
Z - tensor of even order N with a regular dimension of K.
M - matrix unfolding of tensor Z.
'''
N = Z.ndim
K = Z.shape[0]
if split is None:
split = N//2
#bitify = lambda x, K: np.sum(K**np.arange(x.size)*x)
A = np.zeros((K**split, K**(N-split)))
for ind in np.ndindex(Z.shape):
coord1 = ind[:split]
coord2 = ind[split:]
A[bitify(coord1, K), bitify(coord2, K)] = np.log(np.maximum(Z[ind], 0.))
return A
def full2TT(A, maxrank=np.inf, normalized=False):
Z = A
k = A.shape[0]
ndim = A.ndim
G = []
K = []
rprev = 1
ranks = [1]
for d in range(1,ndim+1):
U, S, V = np.linalg.svd(Z.reshape([rprev*k, k**(ndim-d)]), full_matrices=0)
#print(S.min())
r = np.min([np.sum(~np.isclose(S,0.,1e-10)), maxrank]).astype('int16')
Z = S[:r,None]*(V[:r, :])
#r = S.size
ranks += [r]
G += [U[:, :r].reshape(rprev,k,r)]
K += [U[:, :r]]
rprev = r
G[-1] *= Z
cores = Core(ndim, k, ranks, cores=[tf.transpose(g,[1,0,2]) for g in G])
return cores, MPS(ndim, k, ranks, cores=cores, normalized=normalized)
def randomorthogonal(shape):
'''Returns a random orthogonal matrix of shape Shape'''
A = np.random.randn(np.maximum(*shape), np.maximum(*shape))
return np.linalg.qr(A)[0][:shape[0], :shape[1]].astype(dtype)
@tffunc(2)
def tfkron(A, B):
'''Takes the kronecker product of A and B'''
return tf.reshape(A[:, None, :, None] * B[None, :, None, :],
(A.shape[0].value*B.shape[0].value,
A.shape[1].value*B.shape[1].value))
@tffunc(1)
def tfkron2(A):
'''Takes the kronecker product of A with itself'''
return tfkron(A, A)
@tffunc(2)
def multikron(A, B):
'''Takes the kronecker product of A and B, iterating over the first index.'''
return tf.stack([tfkron(a, b) for a, b in zip(tf.unstack(A), tf.unstack(B))])
class OrthogonalMatrix:
'''Class constructs orthogonal matrix in Tensorflow as product of
Householder reflections.'''
def __init__(self, N, eye=False):
self.N = N
if eye:
initial = np.eye(N, dtype=dtype)
else:
initial = tf.random_normal((N, N),dtype=dtype)
self._var = tf.Variable(initial)
scales = tf.sqrt(1e-10+tf.reduce_sum(tf.square(self._var),
axis=1, keepdims=True))
self.V = self._var/scales
self.neg_matrix = HouseholderChain(self.V)
def dot(self, A, left_product=True):
if left_product:
return -self.neg_matrix.dot(A)
else:
return -tf.transpose(self.neg_matrix.dot(tf.transpose(A)))
def dense(self):
return self.dot(tf.eye(self.N, dtype=dtype))
class CayleyOrthogonal:
def __init__(self, N):
self.N = N
self._var = tf.Variable(np.random.randn(N, N).astype(dtype))
self.triu = tf.matrix_band_part(self._var, 0, -1)
self.skew = self.triu-tf.transpose(self.triu)
I = tf.eye(N, dtype=dtype)
self.matrix = tf.matrix_solve(I + self.skew,
I - self.skew)
def dot(self, A, left_product=True):
if left_product:
return tf.matmul(self.matrix, A)
else:
return tf.transpose(tf.matmul(self.matrix, A, transpose_b=True))
def dense(self):
return self.matrix
@tffunc(1)
def entropy(P):
return -tf.reduce_sum(P*tf.log(epsilon+P))
@tffunc(2)
def inner_broadcast(density, core, opt_einsum=False):
'''compute M_k=A_k^T*L*A_k'''
if opt_einsum:
M = tf.einsum('su, ksr->kur', density, core)
return tf.einsum('kurb,kut->krt', M, core)
else:
return tf.einsum('krs,su,kut->krt', tf.transpose(core, [0,2,1]), density, core)
@tffunc(2)
def batch_inner_broadcast(density, core, opt_einsum=False):
'''compute M_k=A_k^T*L*A_k'''
if opt_einsum:
M = tf.einsum('bsu,ksr->kurb', density, core)
return tf.einsum('kurb,kut->bkrt', M, core)
else:
return tf.einsum('krs,bsu,kut->bkrt', tf.transpose(core, [0,2,1]), density, core)
@tffunc(2)
def inner_contraction(density, core, weights = None, opt_einsum=False):
'''compute Sum_k w_k*A_k^T*L*A_k'''
if opt_einsum:
if weights is not None:
M = tf.einsum('su,ksr->kur', density, core)
M = tf.einsum('kur,kut->krt', M, core)
return tf.einsum('krt,k->rt', M, weights)
else:
M = tf.einsum('su,ksr->kur', density, core)
return tf.einsum('kur,kut->rt', M, core)
else:
if weights is not None:
return tf.reduce_sum(tf.reshape(weights, (-1, 1, 1)) * inner_broadcast(density, core), axis=0)
else:
return tf.einsum('krs,su,kut', tf.transpose(core, [0,2,1]), density, core)
@tffunc(2)
def batch_inner_contraction(density, core, weights = None, opt_einsum=False):
'''compute Sum_k w_k*A_k^T*L*A_k'''
if opt_einsum:
if weights is not None:
M = tf.einsum('bsu,ksr->kurb', density, core)
M = tf.einsum('kurb,kut->krtb', M, core)
return tf.einsum('krtb,bk->brt', M, weights)
else:
M = tf.einsum('kut,ksr->surt', core, core)
return tf.einsum('surt,bsu->brt', M, density)
else:
if weights is not None:
return tf.einsum('bkij,bk->bij', batch_inner_broadcast(density, core), weights)
else:
return tf.einsum('krs,bsu,kut', tf.transpose(core, [0,2,1]), density, core)
def packmps(name, mps, sess=None):
mps_metadata = {
'N': mps.N,
'K': mps.K,
'ranks': mps.ranks,
'normalized': mps.normalized,
'multi_temp': mps.multi_temp
}
core_type = mps.raw.__class__
core_metadata = {
'N': mps.N,
'K': mps.K,
'ranks': mps.ranks,
}
if core_type is Canonical:
core_metadata.update({
'left': mps.raw.left_canonical,
'initials': mps.raw.initials,
'orthogonalstyle': mps.raw.orthogonalstyle
})
elif (core_type is CanonicalPermutationCore or
core_type is CanonicalPermutationCore2):
core_metadata.update({'orthogonalstyle': mps.raw.orthogonalstyle})
elif (core_type is SwapInvariant):
core_metadata.update({'orthogonalstyle': mps.raw.orthogonalstyle})
core_metadata.pop('K')
#saver = tf.train.Saver(mps.raw.params(), max_to_keep=None)
basic_metadata = {'core_type': core_type, 'name': name}#, 'save_path': saver.save(sess, folder + name + '.ckpt')}
if sess is None:
sess = tf.get_default_session()
hardcopy = [sess.run(param) for param in mps.raw.params()]
tune_metadata = {'temperature': sess.run(mps.temperatures), 'nu': sess.run(mps.nu)}
metadata = {'basic': basic_metadata, 'hardcopy': hardcopy,
'core': core_metadata, 'mps': mps_metadata, 'tune': tune_metadata}
return metadata
def dictpack(name, dictionary, folder='', sess=None):
new_d = {key: packmps(name+'_key{}'.format(key), value) for key, value in dictionary.items()}
with open(folder + name+'.pkl', 'wb') as handle:
pickle.dump(new_d, handle, protocol=pickle.HIGHEST_PROTOCOL)
def unpackmps(metadata, sess=None):
cores = metadata['basic']['core_type'](**metadata['core'])
mps = MPS(**metadata['mps'], cores=cores)
mass_assign = ([tf.assign(var, value)
for var, value in
zip(cores.params(), metadata['hardcopy'])] +
[tf.assign(var, value)
for var, value in
zip(cores.params(), metadata['hardcopy'])])
mass_assign += [mps.set_nu(metadata['tune']['nu'])]
if metadata['mps']['multi_temp']:
mass_assign += [mps.set_temperature(metadata['tune']['temperature'])]
else:
mass_assign += [mps.set_temperature(metadata['tune']['temperature'][0])]
if sess is None:
sess = tf.get_default_session()
sess.run(mass_assign)
return (mps, cores, mass_assign, metadata)
class Initializer:
'''class for co-initializing several sets of cores, as well as saving and restoring from checkpoints.'''
def __init__(self, list_of_cores):
self.cores = list_of_cores
self.init_cores = {}
self.matchers = []
self.randomizers = []
self.checkpoints = {}
self.init_checkpoints = {}
for core in self.cores:
key = (core.N, core.K, core.ranks, core.__class__)
try:
self.matchers += [core.match(self.init_cores[key])]
except KeyError:
self.init_cores[key] = key[-1](key[0],key[1],key[2])
self.matchers += [core.match(self.init_cores[key])]
self.randomizers += [self.init_cores[key].randomize_op()]
def randomize(self):
return tf.group(self.randomizers)
def match(self):
return tf.group(self.matchers)
def checkpoint_init(self, key, sess=None):
if sess is None:
sess = tf.get_default_session()
self.init_checkpoints[key] = {}
for initkey, initcore in self.init_cores.items():
self.init_checkpoints[key][initkey] = [sess.run(param) for param in initcore.params()]
def restore_init(self, key):
for initkey, initcore in self.init_cores.items():
mass_assign = [tf.assign(var, value) for var, value in zip(initcore.params(), self.init_checkpoints[key][initkey])]
return tf.group(mass_assign)
def checkpoint_cores(self, key, sess=None):
if sess is None:
sess = tf.get_default_session()
self.checkpoints[key] = {}
for core in self.cores:
self.checkpoints[key][core] = [sess.run(param) for param in core.params()]
def restore_cores(self, key):
for core in self.cores:
mass_assign = [tf.assign(var, value) for var, value in zip(core.params(), self.checkpoints[key][core])]
return tf.group(mass_assign)
class MPS:
"""
Instances represent discrete distributions over N discrete random variables
taking values in a finite set of K elements. The distribution is implicitly defined
in terms of a K x ... x K (N times) tensor, which is represented as a squared
matrix product state (equiv. tensor train).
The representation guarantees positivity and allows for efficient computation of
the normalization constant, conditionals, and marginals. Based on this it's also
easy to sample from the model using an ancestral sampler.
N - Integer. Number of tensor axes.
K - Integer. Dimensionality along each axis.
ranks - Iterable of integers. Rank of matrices. The matrices in the i'th core have
rank ranks[i] x ranks[i+1].
cores (None) - Object of type Core. Its .cores field should be an
iterable of order-3 Tensorflow tensors of length N.
.cores[i] should have shape K x ranks[i] x ranks[i+1].
normalized (True) - Boolean. If true, the tensor is normalized to 1.
"""
def __init__(self, N, K, ranks, cores=None, normalized=True, multi_temp=False):
self.N = N
self.K = K
self.ranks = ranks
self.normalized = normalized
self.multi_temp = multi_temp
with tf.name_scope("auxiliary"):
if cores:
self.raw = cores
else:
self.raw = Core(N, K, ranks, cores)
self.right_canonical = self.raw.right_canonical
self.left_canonical = self.raw.left_canonical
if self.right_canonical or self.left_canonical:
self.cores = self.raw.cores
else:
self.cores = self.raw.scaledcores((1./tf.sqrt(self._scale()))
if normalized else
tf.convert_to_tensor(1., dtype=dtype))
self._nuvar = tf.Variable(1., dtype=dtype)
self.nu = tf.identity(self._nuvar)
self._mintemp = 0.01
if multi_temp:
self._tempvar = tf.Variable(np.log(np.exp(0.5)-1.)*np.ones(N), dtype=dtype)
self.temperatures = self._mintemp + tf.nn.softplus(self._tempvar)
else:
self._tempvar = tf.Variable(np.log(np.exp(0.5-self._mintemp)-1.), dtype=dtype)
self.temperatures = self._mintemp + tf.nn.softplus(self._tempvar)*tf.ones(N, dtype=dtype)
self.softgate = lambda z: tf.nn.softmax(z/self.temperature, dim=-1) #scaled softmax
with tf.name_scope("marginalization"):
with tf.name_scope("auxiliary"):
flip_cores = [tf.transpose(core, [0,2,1])
for core in self.cores[-1::-1]]
initial = tf.ones((1., 1.), dtype=dtype)
inner_marg = [tf.einsum('kri,krj->ij',
self.cores[0], self.cores[0])]
for core in self.cores[1:-1]:
inner_marg += [inner_contraction(inner_marg[-1], core)]
outer_marg = [tf.einsum('kir,kjr->ij',
self.cores[-1], self.cores[-1])]
for core in flip_cores[1:-1]:
outer_marg += [inner_contraction(outer_marg[-1], core)]
#add boundary elements (1-vectors) and remove full products
self.inner_marginal = [initial, *inner_marg]
self.outer_marginal = [*outer_marg[-1::-1], initial]
def set_temperature(self, value):
return tf.assign(self._tempvar, np.log(np.exp(value-self._mintemp)-1.))
def set_nu(self, value):
return tf.assign(self._nuvar, value)
@tfmethod(1)
def contraction(self, Z, normalized=True):
"""
Compute Sum_I (Prod_n z_{n, I(n)}) T_I where I ranges over
all indices of the tensor.
"""
if normalized:
cores = self.cores
else:
cores = self.raw.cores
S = tf.ones((1, 1), dtype=dtype)
for core, z in zip(cores, tf.unstack(Z)):
S = inner_contraction(S, core, z)
return tf.squeeze(S)
@tfmethod(1)
def batch_contraction(self, Z, normalized=True):
if normalized:
cores = self.cores
else:
cores = self.raw.cores
batches = Z.shape[0]
S = tf.ones((batches, 1, 1), dtype=dtype)
for core, z in zip(cores, tf.unstack(Z, axis=1)):
S = batch_inner_contraction(S, core, z)
return tf.reshape(S, (-1,))
@tfmethod(1)
def batch_root(self, Z):
batches = Z.shape[0]
S = tf.ones((batches, 1), dtype=dtype)
for core, z in zip(self.cores, tf.unstack(Z, axis=1)):
S = tf.einsum('bi,kij,bk->bj', S, core, z)
return tf.reshape(S, (-1,))
@tfmethod(1)
def batch_logp(self, Z):
return tf.log(epsilon+self.batch_contraction(Z, normalized=True))
@tfmethod(0)
def softsample(self, nsamples=1):
"""Produce a single NxK sample from the induced dMPS, defined as the
implicit generative model where sample 1 is drawn from the concrete
relaxation of the marginal, and sample 2 (and so on) is drawn from
the concrete relaxation of q(x2|x1), where the conditioning is soft:
if p(x2=k|x1=i)=Tr[G_k^T*L_i*G_k*R] is the true conditional (with R
containing the marginalization information), softsample conditions on
Lhat=sum L_i*x1[i] so that the conditioning is correct if x1 is
concentrated on one value.
Returns:
Z: NxK tensor. A sample from the shadow MPS.
"""
shadowcondition = tf.ones((nsamples, 1, 1), dtype=dtype)
shadowsamples = []
if self.left_canonical:
sequence = zip([tf.transpose(c, [0,2,1]) for c in self.cores[-1::-1]],
self.inner_marginal[-1::-1])
else:
sequence = zip(self.cores, self.outer_marginal)
for index, (core, marginal) in enumerate(sequence):
with tf.name_scope("conditional_{}".format(index)):
if self.right_canonical or self.left_canonical:
shadowdistribution = tf.trace(
batch_inner_broadcast(shadowcondition, core))
else:
shadowdistribution = tf.einsum(
'bkij,ji', batch_inner_broadcast(shadowcondition, core),
marginal)
with tf.name_scope("sample_{}".format(index)):
shadowreparam = CategoricalReparam(
tf.log(epsilon+shadowdistribution),
temperature=self.temperatures[index])
shadowsample = shadowreparam.gatedz
shadowsamples += [shadowsample]
with tf.name_scope("update_{}".format(index)):
shadowupdate = tf.einsum('kij,bk', core,
shadowsample)
shadowcondition = tf.einsum('bik,bkl,blj->bij',
tf.transpose(shadowupdate, [0,2,1]),
shadowcondition, shadowupdate)
if self.left_canonical:
shadowsamples = shadowsamples[-1::-1]
shadowb = tf.transpose(tf.stack(shadowsamples), [1,0,2])
return tf.squeeze(shadowb)
@tfmethod(0)
def get_samplers(self, nsamples=1, coupled=False):
condition = tf.ones((nsamples, 1, 1), dtype=dtype)
samplers = []
if self.left_canonical:
sequence = zip([tf.transpose(c, [0,2,1]) for c in self.cores[-1::-1]],
self.inner_marginal[-1::-1])
else:
sequence = zip(self.cores, self.outer_marginal)
for index, (core, marginal) in enumerate(sequence):
with tf.name_scope("conditional_{}".format(index)):
if self.right_canonical or self.left_canonical:
distribution = tf.trace(
batch_inner_broadcast(condition, core))
else:
distribution = tf.einsum(
'bkij,ji', batch_inner_broadcast(condition, core),
marginal)
with tf.name_scope("sample_{}".format(index)):
reparam = CategoricalReparam(
tf.log(epsilon+distribution),
temperature=self.temperatures[index], coupled=coupled)
samplers += [reparam]
with tf.name_scope("update_{}".format(index)):
update = tf.einsum('kij,bk', core,
reparam.b)
condition = tf.einsum('bik,bkl,blj->bij',
tf.transpose(update, [0,2,1]),
condition, update)
if self.left_canonical:
return samplers[-1::-1]
else:
return samplers
@tfmethod(0)
def get_shadowsamplers(self, samplers):
nsamples = samplers[0].b.shape[0]
condition = tf.ones((nsamples, 1, 1), dtype=dtype)
shadowsamplers = []
if self.left_canonical:
sequence = zip([tf.transpose(c, [0,2,1]) for c in self.cores[-1::-1]],
self.inner_marginal[-1::-1], samplers[-1::-1])
else:
sequence = zip(self.cores, self.outer_marginal, samplers)
for index, (core, marginal, sampler) in enumerate(sequence):
with tf.name_scope("conditional_{}".format(index)):
if self.right_canonical or self.left_canonical:
distribution = tf.trace(
batch_inner_broadcast(condition, core))
else:
distribution = tf.einsum(
'bkij,ji', batch_inner_broadcast(condition, core),
marginal)
with tf.name_scope("sample_{}".format(index)):
reparam = CategoricalReparam(
tf.log(epsilon+distribution),
noise=sampler.u, cond_noise=sampler.v,
temperature=self.temperatures[index])
shadowsamplers += [reparam]
with tf.name_scope("update_{}".format(index)):
#shadowsampler difference
update = tf.einsum('kij,bk', core,
reparam.gatedz)
condition = tf.einsum('bik,bkl,blj->bij',
tf.transpose(update, [0,2,1]),
condition, update)
if self.left_canonical:
return shadowsamplers[-1::-1]
else:
return shadowsamplers
@tfmethod(0)
def shadowrelax(self, nsamples=1,samplers=None):
if samplers is None:
samplers = self.get_samplers(nsamples)
else:
assert(samplers[0].param.shape[0]==nsamples)
bsamples = []
zsamples = []
zbsamples = []
shadowsamplers = self.get_shadowsamplers(samplers)
condition = tf.ones((nsamples, 1, 1), dtype=dtype)
#flip to exploit canonicity
if self.left_canonical:
sequence = zip([tf.transpose(c, [0,2,1]) for c in self.cores[-1::-1]],
self.inner_marginal[-1::-1], samplers[-1::-1], shadowsamplers[-1::-1])
else:
sequence = zip(self.cores, self.outer_marginal, samplers, shadowsamplers)
for index, (core, marginal, sampler, shadowsampler) in enumerate(sequence):
with tf.name_scope('conditional_{}'.format(index)):
if self.right_canonical or self.left_canonical:
distribution = tf.trace(
batch_inner_broadcast(condition, core))
else:
distribution = tf.einsum(
'bkij,ji', batch_inner_broadcast(condition, core),
marginal)
with tf.name_scope('sample_{}'.format(index)):
conditionalzb = shadowsampler.softgate(tf.log(epsilon+distribution) + sampler.zb - sampler.param, shadowsampler.temperature)
bsamples += [sampler.b]
zsamples += [shadowsampler.gatedz]
zbsamples += [conditionalzb]
with tf.name_scope('update_{}'.format(index)):
update = tf.einsum('kij,bk', core, conditionalzb)
condition = tf.einsum('bik,bkl,blj->bij',
tf.transpose(update, [0,2,1]),
condition, update)
#flip back
if self.left_canonical:
bsamples = bsamples[-1::-1]
zsamples = zsamples[-1::-1]
zbsamples = zbsamples[-1::-1]
collect = lambda samples: tf.transpose(tf.stack(samples), [1,0,2])
return (collect(bsamples), collect(zsamples), collect(zbsamples))
@tfmethod(0)
def sample(self, nsamples=1, doshadowsample=False, coupled=False, raw=False):
'''Runs ancestral sampling routine and calculates necessary
reparameterized quantities for a REBAR estimator.
See softsample() for more info on shadow MPS.
Args:
shadowsample (defaults to False): Boolean. If False, return a
sample from MPS, if True, return a tuple of samples from MPS
and the shadow MPS.
Returns:
b: NxK tensor. A sample from the MPS.
shadowb (if doshadowsample==True)): NxK tensor. A sample from the
relaxed MPS where samples are continuous and draws from a
concrete distribution, and conditioning is produced by
averaging over the core relative to the sample.
Generating noise tied to the noise producing b.
conditionalshadowb (if doshadowsample==True): Same as shadowb, except
conditioned on the vaulue of b being observed.
'''
condition = tf.ones((nsamples, 1, 1), dtype=dtype)
samples = []
if doshadowsample:
shadowcondition = tf.ones((nsamples, 1, 1), dtype=dtype)
shadowsamples = []
conditionalshadowsamples = []
if self.left_canonical:
sequence = zip([tf.transpose(c, [0,2,1]) for c in self.cores[-1::-1]],
self.inner_marginal[-1::-1])
else:
sequence = zip(self.cores, self.outer_marginal)
for index, (core, marginal) in enumerate(sequence):
if self.right_canonical or self.left_canonical:
distribution = tf.trace(
batch_inner_broadcast(condition, core))
else:
distribution = tf.einsum(
'bkij,ji', batch_inner_broadcast(condition, core),
marginal)
reparam = CategoricalReparam(
tf.log(epsilon+distribution),
temperature=self.temperatures[index])
sample = reparam.b
samples += [sample]
update = tf.einsum('kij,bk', core,
sample)
condition = tf.einsum('bik,bkl,blj->bij',
tf.transpose(update, [0,2,1]),
condition, update)
if doshadowsample:
if self.right_canonical or self.left_canonical:
shadowdistribution = tf.trace(
batch_inner_broadcast(shadowcondition, core))
else:
shadowdistribution = tf.einsum(
'bkij,ji', batch_inner_broadcast(shadowcondition, core),
marginal)
shadowreparam = CategoricalReparam(
tf.log(shadowdistribution) -
tf.reduce_logsumexp(shadowdistribution, keepdims=True),
noise=reparam.u, cond_noise=reparam.v,
temperature=self.temperatures[index])
shadowsample = shadowreparam.gatedz
shadowsamples += [shadowsample]
zb = reparam.zb
sb = zb + shadowreparam.param - reparam.param
conditionalshadowsample = shadowreparam.softgate(
sb, shadowreparam.temperature)
conditionalshadowsamples += [conditionalshadowsample]
shadowupdate = tf.einsum('kij,bk', core, shadowsample)
shadowcondition = tf.einsum('bik,bkl,blj->bij',
tf.transpose(shadowupdate, [0,2,1]),
shadowcondition, shadowupdate)
if self.left_canonical:
samples = samples[-1::-1]
b = tf.transpose(tf.stack(samples), [1,0,2])
if doshadowsample:
if self.left_canonical:
shadowsamples = shadowsamples[-1::-1]
conditionalshadowsamples = conditionalshadowsamples[-1::-1]
shadowb = tf.transpose(tf.stack(shadowsamples), [1,0,2])
conditionalshadowb = tf.transpose(tf.stack(conditionalshadowsamples), [1,0,2])
return (b, shadowb, conditionalshadowb) if doshadowsample else b
@tfmethod(1)
def gibbsconditionals(self, Z, logprob=True, normalized=True):
#cores = [tf.einsum('kij,k', core, tf.squeeze(z))
# for z, core in zip(tf.unstack(Z), self.cores)]
inner_condition = tf.ones((1,1), dtype=dtype)
inner_conditions = [inner_condition]
for z, kcore in zip(tf.unstack(Z), self.cores):
core = tf.einsum('kij,k', kcore, tf.squeeze(z))
inner_condition = tf.einsum('ik,kl,lj', tf.transpose(core),
inner_condition, core)
inner_conditions.append(inner_condition)
outer_condition = tf.ones((1,1), dtype=dtype)
conditionals = []
for z, kcore, inner_condition in reversed(list(zip(tf.unstack(Z), self.cores, inner_conditions[:-1]))):
conditional = inner_broadcast(inner_condition, kcore)
conditionals.append(tf.einsum('kij,ji',conditional, outer_condition))
outer_condition = inner_contraction(outer_condition, tf.transpose(kcore, [0, 2, 1]), tf.squeeze(z))
conditionals = tf.stack(conditionals[-1::-1])
if logprob:
conditionals = tf.log(conditionals)
if normalized:
conditionals = conditionals - tf.reduce_logsumexp(conditionals,
axis=-1,
keepdims=True)
else:
if normalized:
condititionals = conditionals/tf.reduce_sum(conditionals,
axis=-1,
keepdims=True)
return conditionals
def collocation(self, nsamples=100000):
if nsamples > 0:
z = self.sample(nsamples)
return tf.einsum('bik,bjk', z, z)/nsamples
else:
transfers = [multikron(core, core) for core in self.cores]
marginals = [tf.reduce_sum(transfer, axis=0) for transfer in transfers]
A = []#tf.zeros((self.N, self.N), dtype=dtype)
for i,j in np.ndindex((self.N, self.N)):
if i == j:
a = 1.
else:
a = 0.
for k in range(self.K):
factors = [(marginals[l] if (l!=i and l!=j) else transfers[l][k]) for l in range(self.N)]
x = factors[0]
for factor in factors[1:]:
x = tf.matmul(x, factor)
a += x
A.append(a)
# A[i,j] = self.K*tf.foldl(tf.matmul, factors)
return tf.reshape(tf.stack(A), (self.N, self.N))
def covariance(self, nsamples=100000, blockgroup=True, scale=False):
z = self.sample(nsamples)
if blockgroup:
z = tf.reshape(tf.transpose(z,[0,2,1]), (z.shape[0], -1))
m = tf.reshape(tf.transpose(self.marginals()), (-1,1))
else:
z = tf.reshape(z, (z.shape[0], -1))
m = tf.reshape(self.marginals(), (-1,1))
cov = tf.matmul(z, z, transpose_a=True)/nsamples - m*tf.transpose(m)
if scale:
var = m*(1.-m)
scale = tf.sqrt(var*tf.transpose(var))
return cov/scale
else:
return cov
@tfmethod(0)
def marginals(self, uniform=False):
if uniform:
return tf.ones((self.N, self.K))/self.K
if self.left_canonical:
return tf.stack([tf.einsum('kir,krs,si->k',
tf.transpose(core,[0, 2, 1]),
core, outer_marg)
for core, outer_marg in
zip(self.cores,
self.outer_marginal)])
elif self.right_canonical:
return tf.stack([tf.einsum('kiu,ur,kri->k',
tf.transpose(core,[0, 2, 1]),
inner_marg, core)
for core, inner_marg in
zip(self.cores,
self.inner_marginal)])
else:
return tf.stack([tf.einsum('kiu,ur,krs,si->k',
tf.transpose(core,[0, 2, 1]),
inner_marg, core, outer_marg)
for core, inner_marg, outer_marg in
zip(self.cores,
self.inner_marginal,
self.outer_marginal)])
@tfmethod(0)
def marginalentropy(self):
'''calculate entropy of marginals'''
marginals = self.marginals()
return entropy(marginals)
@tfmethod(1)
def elbo(self, samples, f, fold=False, marginal=True, invtemp=1., cvweight=1., report=False):
'''calculate ELBO or another entropy-weighted expectation using nsamples MC samples'''
if fold:
llk = tf.map_fn(f, samples)
else:
llk = f(samples)
if marginal:
marginals = self.marginals()
marginalentropy = -tf.reduce_sum(marginals * tf.log(epsilon+marginals))
marginalcv = (marginalentropy +
tf.reduce_sum(samples *
tf.log(epsilon+marginals)[None, :, :],
axis=[1, 2]))
else:
marginalcv = 0.
entropy = -tf.log(epsilon+self.batch_contraction(samples))
elbo = llk + entropy + cvweight*marginalcv
objective = llk + invtemp*(entropy + cvweight*marginalcv)
if report:
return (objective, elbo, llk, entropy, marginalentropy, marginalcv)
else:
return elbo
@tfmethod(0)
def elbowithmodes(self, f, modes, nsamples=1, fold=False, marginal=True, invtemp=1., cvweight=1., report=False):
'''calculate ELBO or another entropy-weighted expectation using nsamples MC samples'''
samples = self.softsample(nsamples)
if fold:
llk = tf.map_fn(f, samples)
modellk = tf.map_fn(f, modes)
else:
llk = f(samples)
modellk = f(modes)
if marginal:
marginals = self.marginals()
marginalentropy = -tf.reduce_sum(marginals * tf.log(epsilon+marginals))
marginalcv = (marginalentropy +
tf.reduce_sum(samples *
tf.log(epsilon+marginals)[None, :, :],
axis=[1, 2]))
else:
marginalcv = 0.
entropy = -tf.log(epsilon+self.batch_contraction(samples))
modeweight = self.batch_contraction(modes)
modeentropy = -tf.log(epsilon+modeweight)
elbo = llk + entropy + cvweight*marginalcv
objective = llk + invtemp*(entropy + cvweight*marginalcv) + tf.reduce_sum(modeweight*(modellk+modeentropy))
if report:
return (objective, elbo, llk, entropy, marginalentropy, marginalcv)
else:
return objective
#def totalcorrelation(self, nsamples=5):
# sample =
# return tf.log(self.contraction())
@tfmethod(0)
def pred(self, f, nsamples=1, fold=False):
'''calculate expectation of function f over nsamples samples from model'''
samples = self.sample(nsamples)
if fold:
llk = tf.map_fn(f, samples)
else:
llk = f(samples)
return llk
@tfmethod(0)
def populatetensor(self):
'''Convert MPS tensor to a dense format.
Returns:
Z - tensor of order N with each axis having length K.
'''
def standardcore(C):
return tf.transpose(C, [1,0,2])
def core2orthU(C, rank):
return tf.reshape(C, (-1, rank))
def core2orthV(C, rank):
return tf.reshape(C, (rank, -1))
Z = standardcore(self.cores[0])
for core, rank in zip(self.cores[1:], self.ranks[1:]):
stdcore = standardcore(core)
Z = tf.matmul(core2orthU(Z, rank), core2orthV(stdcore, rank))
Z = tf.square(tf.reshape(Z, [self.K,]*self.N))
return tf.real(Z)
@tfmethod(0)
def _scale(self):
return tf.identity(self.contraction(tf.ones((self.N, self.K),
dtype=dtype),
normalized=False),
name="scale")
def params(self):
return self.raw.params()
def var_params(self):
return [self._tempvar, self._nuvar]
class unimix(MPS):
def __init__(self, N, K, ranks, cores=None, normalized=True, multi_temp=False):
super().__init__(N, K, ranks, cores=cores, normalized=normalized, multi_temp=multi_temp)
self.logalpha_var = tf.Variable(0., dtype=dtype)
self.logalpha = -tf.nn.softplus(self.logalpha_var)
self.log1malpha = -tf.nn.softplus(-self.logalpha_var)
self.log_uniform = tf.convert_to_tensor(-self.N*np.log(self.K), dtype=dtype)
@tfmethod(1)
def batch_logp_mps(self, Z):
return super().batch_logp(Z)
@tfmethod(1)
def batch_logp(self, Z):
def vec_scalar_logsumexp(vec, scalar):
return tf.reduce_logsumexp(tf.stack([vec, scalar*tf.ones(vec.shape, dtype=dtype)],axis=1),axis=1)
return vec_scalar_logsumexp(self.logalpha + super().batch_logp(Z),
self.log1malpha + self.log_uniform + tf.reduce_logsumexp(Z))
@tfmethod(1)
def batch_contraction(self, Z, normalized=True):
return tf.exp(self.log1malpha + self.log_uniform + tf.reduce_logsumexp(Z)) + tf.exp(self.logalpha) * super().batch_contraction(Z, normalized=normalized)
@tfmethod(1)
def elbo(self, samples, f, fold=False, marginal=False, cvweight=1.):
'''calculate ELBO or another entropy-weighted expectation using nsamples MC samples'''
gumbels = -tf.log(-tf.log(tf.random_uniform(samples.shape)))
usamples = tf.one_hot(tf.argmax(gumbels, axis=-1), self.K, dtype=dtype)
if fold:
llk = tf.map_fn(f, samples)
ullk = tf.map_fn(f, usamples)
else:
llk = f(samples)
ullk = f(usamples)
if marginal:
marginals = self.marginals()
marginalentropy = -tf.reduce_sum(marginals * tf.log(epsilon+marginals))
marginalcv = (marginalentropy +
tf.reduce_sum(samples *
tf.log(epsilon+marginals)[None, :, :],
axis=[1, 2]))
else:
marginalcv = 0.
entropy = -self.batch_logp(samples)
uentropy = -self.batch_logp(usamples)
return tf.exp(self.logalpha)*(llk + entropy) + tf.exp(self.log1malpha)*(ullk + uentropy) + cvweight*marginalcv
def marginals(self):
return tf.exp(self.logalpha)*super().marginals() + tf.exp(self.log1malpha)/self.K
@tfmethod(0)
def populatetensor(self):
q = super().populatetensor()
mixq = tf.exp(self.logalpha)*q
mixuniform = tf.exp(self.log1malpha + self.log_uniform)
return mixq + mixuniform
@tfmethod(1)
def set_alpha_op(self, alpha):
logalpha_hat = tf.log(alpha)
return tf.assign(self.logalpha_var, tf.log(tf.exp(-logalpha_hat)-1.))
def params(self):
return super().params() + [self.logalpha_var]
class unimixIS(unimix):
def batch_logp(self, Z):
return tf.log(self.mps.batch_contraction(Z))
@tfmethod(1)
def batch_logp_proposal(self, Z):
def vec_scalar_logsumexp(vec, scalar):
return tf.reduce_logsumexp(tf.stack([vec, scalar*tf.ones(vec.shape, dtype=dtype)],axis=1),axis=1)
logp = tf.reshape(tf.log(self.mps.batch_contraction(Z)), (-1,))
return vec_scalar_logsumexp(self.logalpha + logp,
self.log1malpha + self.log_uniform)
@tfmethod(1)
def elbo_q(self, samples, f, fold=False):
'''calculate ELBO or another entropy-weighted expectation using nsamples MC samples'''
if fold:
llk = tf.map_fn(f, samples)
else:
llk = f(samples)
logq = self.batch_logp(samples)
correction = self.logalpha + logq - self.batch_logp_proposal(samples)
elbo = tf.exp(correction)*(llk - logq)
return elbo
@tfmethod(1)
def elbo_uni(self, samples, f, fold=False):
'''calculate ELBO or another entropy-weighted expectation using nsamples MC samples'''
if fold:
llk = tf.map_fn(f, samples)
else:
llk = f(samples)
logq = self.batch_logp(samples)
correction = self.log1malpha + logq - self.batch_logp_proposal(samples)
elbo = tf.exp(correction)*(llk - logq)