-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTNutils.py
2395 lines (2018 loc) · 85.2 KB
/
TNutils.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
#################
#### IMPORTS ####
#################
# Arrays
import numpy as np
import cytoolz
import dask as ds
from dask.array import Array as daskarr
import dask.array as da
# Deep Learning stuff
import torch
import torchvision
import torchvision.transforms as transforms
# Images display and plots
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.colors import ListedColormap
import matplotlib.pylab as pl
# Fancy progress bars
import tqdm.notebook as tq
# Tensor Network Stuff
import quimb.tensor as qtn # Tensor Network library
import quimb
from collections import deque
# Profiling
import cProfile, pstats, io
from pstats import SortKey
import functools
import collections
import opt_einsum as oe
import itertools
import pydash as _pd
import copy
import os
#######################################################
'''
Wrapper for type checks.
While defining a function, you can add the wrapper
stating the expected types:
> @arg_val(class_1, class_2, ...)
> def function(a, b, ...):
'''
def arg_val(*args):
def wrapper(func):
def validating(*_args):
if any(type(_arg)!=arg for _arg, arg in zip(_args,args)):
raise TypeError('wrong type!')
return func(*_args)
return validating
return wrapper
def pro_profiler(func):
'''Generic profiler. Expects an argument-free function.
e. g. func = lambda: learning_epoch_SGD(mps, imgs, 3, 0.1).
Prints and returns the profiling report trace.'''
# TODO: adapt to write trace to file
pr = cProfile.Profile()
pr.enable()
func()
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
return s
class mps_lr:
def __init__(self, mps, lr0, momentum, s_factor):
self.sites = len(mps.tensors)
self.lr0 = lr0
self.curr_lr = self.lr0
self.momentum = momentum
self.t = 0
self.s_factor = s_factor
self.past_grad = (self.sites-1)*[0]
def clear(self):
self.t = 0
def compute_lr(self, t):
'''
Lr will be annealed each epoch through an exponential function that
takes into account the baseline value
'''
return ((self.lr0)*np.exp(-self.s_factor*self.t ) )
def new_epoch(self):
'''
Update curr lr to the next timestep
'''
self.t = self.t + 1
self.curr_lr = self.compute_lr(self.t)
def J(self, left_index, dNLL):
'''
J^{k+1} = \beta J^{k} + dNLL^{k}
A^{k+1} = A^{k} - lr* J^{k+1}
'''
if self.t > 0:
J = self.momentum * self.past_grad[left_index] + dNLL
else:
J = dNLL
self.past_grad[left_index] = np.mean(dNLL.data)
return J
# ___
# |_ |
# _| |_ _
# |_____|_| MNIST FUNCTIONS
#######################################################
def get_data(train_size = 1000, test_size = 100, grayscale_threshold = .5):
'''
Prepare the MNIST dataset for the training algorithm:
* Choose randomly a subset from the whole dataset
* Flatten each image to mirror the mps structure
* Normalize images from [0,255] to [0,1]
* Apply a threshold for each pixels so that each value
below that threshold are set to 0, the others get set to 1.
For this algorithm we will only deal to binary states {0,1}
instead of a range from 0 to 1
'''
# Download all data
mnist = torchvision.datasets.MNIST('classifier_data', train=True, download=True,
transform = transforms.Compose([transforms.ToTensor()]) )
# Convert torch.tenor to numpy
npmnist = mnist.data.numpy()
# Check of the type of the sizes
#if ((type(train_size) != int) or (type(test_size) != int)):
# raise TypeError('train_size and test_size must be INT')
# Check if the training_size and test_size requested are bigger than
# the MNIST whole size
if ( (train_size + test_size) > npmnist.shape[0] ):
raise ValueError('Subset too big')
# Check of the positivity of sizes
if ( (train_size <= 0) or (test_size <= 0) ):
raise ValueError('Size of training set and test set cannot be negative')
# Choose just a subset of the data
# Creating a mask by randomly sampling the indexes of the full dataset
subset_indexes = np.random.choice(np.arange(npmnist.shape[0]), size=(train_size + test_size),
replace=False, p=None)
# Apply the mask
npmnist = npmnist[subset_indexes]
# Flatten every image
npmnist = np.reshape(npmnist, (npmnist.shape[0], npmnist.shape[1]*npmnist.shape[2]))
# Normalize the data from 0 - 255 to 0 - 1
npmnist = npmnist/npmnist.max()
# As in the paper, we will only deal with {0,1} values, not a range
if ((grayscale_threshold <= 0) or (grayscale_threshold >= 1)):
raise ValueError('grayscale_threshold must be in range ]0,1[')
npmnist[npmnist > grayscale_threshold] = 1
npmnist[npmnist <= grayscale_threshold] = 0
# Return training set and test set
return npmnist[:train_size], npmnist[train_size:]
def plot_img(img_flat, shape, flip_color = True, border = False, savefig = '', title=''):
'''
Display the image from the flattened form
'''
# If the image is corrupted for partial reconstruction (pixels are set to -1)
if -1 in img_flat:
img_flat = np.copy(img_flat)
img_flat[img_flat == -1] = 0
plt.figure(figsize = (2,2))
if title != '':
plt.title(title)
# Background white, strokes black
if flip_color:
plt.imshow(1-np.reshape(img_flat,shape), cmap='gray')
# Background black, strokes white
else:
plt.imshow(np.reshape(img_flat,shape), cmap='gray')
if border:
plt.xticks([])
plt.yticks([])
else:
plt.axis('off')
if savefig != '':
# save the picture as svg in the location determined by savefig
plt.savefig(savefig, format='svg')
plt.show()
def partial_removal_img(mnistimg, shape, fraction = .5, axis = 0, half = None):
'''
Corrupt (with -1 values) a portion of an input image (from the test set)
to test if the algorithm can reconstruct it
'''
# Check shape:
if len(shape) != 2 or (shape[0]<1 or shape[1]<1):
raise ValueError('The shape of an image needs two positive integer components')
# Check type:
if [type(mnistimg), type(fraction), type(axis)] != [np.ndarray, float, int]:
raise TypeError('Input types not valid')
# Check the shape of input image
if (mnistimg.shape[0] != shape[0]*shape[1]):
raise TypeError(f'Input image shape does not match, need (f{shape[0]*shape[1]},)')
# Axis can be either 0 (rowise deletion) or 1 (columnwise deletion)
if not(axis in [0,1]):
raise ValueError('Invalid axis [0,1]')
# Fraction must be from 0 to 1
if (fraction < 0 or fraction > 1):
raise ValueError('Invalid value for fraction variable (in interval [0,1])')
mnistimg_corr = np.copy(mnistimg)
mnistimg_corr = np.reshape(mnistimg_corr, shape)
if half == None:
half = np.random.randint(2)
if axis == 0:
if half == 0:
mnistimg_corr[int(shape[0]*(1-fraction)):,:] = -1
else:
mnistimg_corr[:int(shape[0]*(1-fraction)),:] = -1
else:
if half == 0:
mnistimg_corr[:,int(shape[1]*(1-fraction)):] = -1
else:
mnistimg_corr[:,:int(shape[1]*(1-fraction))] = -1
mnistimg_corr = np.reshape(mnistimg_corr, (shape[0]*shape[1],))
return mnistimg_corr
def plot_rec(cor_flat, rec_flat, shape, savefig = '', N = 2):
'''
Display the RECONSTRUCTION
'''
# PREPARING CMAPS
greycmap = pl.cm.Greys
# Get the colormap colors
corrupted_cmap = greycmap(np.arange(greycmap.N))
# Set alpha
corrupted_cmap[:,-1] = np.linspace(0, 1, greycmap.N)
# Create new colormap
corrupted_cmap = ListedColormap(corrupted_cmap)
reccolors = [(1, 0, 0), (1, 1, 1)]
reccmap = LinearSegmentedColormap.from_list('rec', reccolors, N=N)
# If the image is corrupted for partial reconstruction (pixels are set to -1)
cor_flat = np.copy(cor_flat)
cor_flat[cor_flat == -1] = 0
plt.figure(figsize = (2,2))
plt.imshow(1-np.reshape(rec_flat, shape), cmap=reccmap)
plt.imshow(np.reshape(cor_flat, shape), cmap=corrupted_cmap)
plt.axis('off')
if savefig != '':
# save the picture as svg in the location determined by savefig
plt.savefig(savefig, format='svg')
plt.show()
# ____
# |___ \
# __) |
# / __/ _
# |_____(_) MPS GENERAL
#######################################################
@functools.lru_cache(2**12)
def _inds_to_eq(inputs, output):
"""
Conert indexes to the equation of contractions for np.einsum function
"""
symbol_get = collections.defaultdict(map(oe.get_symbol, itertools.count()).__next__).__getitem__
in_str = ("".join(map(symbol_get, inds)) for inds in inputs)
out_str = "".join(map(symbol_get, output))
return ",".join(in_str) + f"->{out_str}"
def tneinsum(tn1,tn2):
'''
Contract tn1 with tn2
It is an automated function that automatically contracts the bonds with
the same indexes.
For simple contractions this function is faster than tensor_contract
or @
'''
inds_i = tuple([tn1.inds, tn2.inds])
inds_out = tuple(qtn.tensor_core._gen_output_inds(cytoolz.concat(inds_i)))
eq = qtn.tensor_core._inds_to_eq(inds_i, inds_out)
data = np.einsum(eq,tn1.data,tn2.data)
return qtn.Tensor(data=data, inds=inds_out)
def tneinsum2(tn1,tn2):
'''
Contract tn1 with tn2
It is an automated function that automatically contracts the bonds with
the same indexes.
For simple contractions this function is faster than tensor_contract
or @
'''
inds_i = tuple([tn1.inds, tn2.inds])
inds_out = tuple(qtn.tensor_core._gen_output_inds(cytoolz.concat(inds_i)))
eq = _inds_to_eq(inds_i, inds_out)
data = np.einsum(eq,tn1.data,tn2.data)
return qtn.Tensor(data=data, inds=inds_out)
@functools.lru_cache(2**12)
def arr_inds_to_eq(inputs, output):
"""
Conert indexes to the equation of contractions for np.einsum function
"""
symbol_get = collections.defaultdict(map(oe.get_symbol, itertools.count()).__next__).__getitem__
in_str = ("".join(map(symbol_get, inds)) for inds in inputs)
out_str = "".join(map(symbol_get, output))
return "i"+",i".join(in_str) + f"->i{out_str}"
def into_data(tensor_array):
return np.array([ten.data.astype(np.float32) for ten in tensor_array])
def _into_data(tensor_array):
op_arr = []
for ten in tensor_array:
op_arr.append(ds.delayed(lambda x: x.data.astype(np.float32))(ten))
data_arr = ds.delayed(lambda x: x)(op_arr).compute()
return data_arr
def into_tensarr(data_arr,inds):
return np.array([qtn.Tensor(data=data,inds=inds) for data in data_arr])
def tneinsum3(*tensor_lists,backend = 'torch'):
'''
Takes arrays of tensors and contracts them element by element.
'''
# Retrieve indeces from the first elements
inds_in = tuple([arr[0].inds for arr in tensor_lists])
# Output indeces
inds_out = tuple(qtn.tensor_core._gen_output_inds(cytoolz.concat(inds_in)))
# Convert into einsum expression with extra index for entries
eq = arr_inds_to_eq(inds_in, inds_out)
# Generate a list of arrays of numpy tensors
tens_data = [into_data(ten) for ten in tensor_lists]
# Extract the shapes
shapes = [tens.shape for tens in tens_data]
# prepare opteinsum reduction expression
expr = oe.contract_expression(eq,*shapes)
# execute and extract
data_arr = expr(*tens_data,backend = backend)
return into_tensarr(data_arr,inds_out)
def initialize_mps(Ldim, bdim = 30, canonicalize = 0):
'''
Initialize the MPS tensor network
1. Create the MPS TN
2. Canonicalization
3. Renaming indexes
'''
# Create a simple MPS network randomly initialized
mps = qtn.MPS_rand_state(Ldim, bond_dim=bdim)
# Canonicalize: use a canonicalize value out of range to skip it (such as -1)
if canonicalize in range(Ldim):
mps.canonize(canonicalize)
# REINDEXING TENSORS FOR A EASIER DEVELOPING
# during initializations, the index will be named using the same notation of the
# Pan Zhang et al paper:
# ___ ___ ___
# |I0|--i0--|I1|--i1-... ...-i(N-1)--|IN|
# | | |
# | v0 | v1 | vN
# V V V
# Reindexing the leftmost tensor
mps = mps.reindex({mps.tensors[0].inds[0]: 'i0',
mps.tensors[0].inds[1]: 'v0'})
# Reindexing the inner tensors through a cycle
for tensor in range(1,len(mps.tensors)-1):
mps = mps.reindex({mps.tensors[tensor].inds[0]: 'i'+str(tensor-1),
mps.tensors[tensor].inds[1]: 'i'+str(tensor),
mps.tensors[tensor].inds[2]: 'v'+str(tensor)})
# Reindexing the last tensor
tensor = tensor + 1
mps = mps.reindex({mps.tensors[tensor].inds[0]: 'i'+str(tensor-1),
mps.tensors[tensor].inds[1]: 'v'+str(tensor)})
return mps
def quimb_transform_img2state(img):
'''
Trasform an image to a tensor network to fully manipulate
it using quimb, may be very slow, use it for checks
'''
# Initialize empty tensor
img_TN = qtn.Tensor()
for k, pixel in enumerate(img):
if pixel == 0: # if pixel is 0, we want to have a tensor with data [0,1]
img_TN = img_TN & qtn.Tensor(data=[0,1], inds=['v'+str(k)], )
else: # if pixel is 1, we want to have a tensor with data [1,0]
img_TN = img_TN & qtn.Tensor(data=[1,0], inds=['v'+str(k)], )
# | | 781 |
# O O ... O
return img_TN
def stater(x,i):
if x in [0,1]:
vec = [int(x), int(not x)]
return qtn.Tensor(vec,inds=(f'v{i}',))
return None
def tens_picture(picture):
'''Converts an array of bits into a list of tensors compatible with a tensor network.'''
tens = [stater(n,i) for i, n in enumerate(picture)]
return np.array(tens)
def left_right_cache(mps,_imgs):
curr_l = np.array(len(_imgs)*[qtn.Tensor()])
curr_l = curr_l.reshape((len(_imgs),1))
for site in range(len(mps.tensors)-1):
machines = np.array(len(_imgs)*[mps[site]])
contr_l = tneinsum3(curr_l[:,-1],machines,_imgs[:,site])
data = into_data(contr_l)
maxa = np.abs(data).max(axis = tuple(range(1,len(data.shape))))
data = data/maxa.reshape((len(_imgs),1))
contr_l = into_tensarr(data,contr_l[0].inds)
contr_l = contr_l.reshape((len(_imgs),1))
curr_l = np.hstack([curr_l,contr_l])
curr_r = np.array(len(_imgs)*[qtn.Tensor()])
curr_r = curr_r.reshape((len(_imgs),1))
for site in range(len(mps.tensors)-1,0,-1):
machines = np.array(len(_imgs)*[mps[site]])
contr_r = tneinsum3(curr_r[:,0],machines,_imgs[:,site])
data = into_data(contr_r)
maxa = np.abs(data).max(axis = tuple(range(1,len(data.shape))))
data = data/maxa.reshape((len(_imgs),1))
contr_r = into_tensarr(data,contr_r[0].inds)
contr_r = contr_r.reshape((len(_imgs),1))
curr_r = np.hstack([contr_r,curr_r])
img_cache = np.array([curr_l,curr_r]).transpose((1,0,2))
return img_cache
def ext_left_right_cache(mps,_imgs):
# WARNING: THIS IS EXTREMELY SLOW.
# It's more convenient to initialize on RAM and convert to dask array
curr_l = da.from_array(len(_imgs)*[qtn.Tensor()], chunks = (len(_imgs)))
curr_l = curr_l.reshape((len(_imgs),1))
for site in range(len(mps.tensors)-1):
machines = np.array(len(_imgs)*[mps[site]])
contr_l = tneinsum3(curr_l[:,-1].compute(),machines,_imgs[:,site])
contr_l = da.from_array(contr_l.reshape((len(_imgs),1)),chunks = (len(_imgs)))
curr_l = da.hstack((curr_l,contr_l))
curr_r = da.from_array(len(_imgs)*[qtn.Tensor()], chunks = (len(_imgs)))
curr_r = curr_r.reshape((len(_imgs),1))
for site in range(len(mps.tensors)-1,0,-1):
machines = np.array(len(_imgs)*[mps[site]])
contr_r = tneinsum3(curr_r[:,0].compute(),machines,_imgs[:,site])
contr_r = da.from_array(contr_r.reshape((len(_imgs),1)),chunks = (len(_imgs)))
curr_r = da.hstack((contr_r,curr_r))
img_cache = da.from_array([curr_l,curr_r],chunks = (1,len(_imgs),1)).transpose((1,0,2))
return img_cache
def sequential_update(mps,_imgs,img_cache,site,going_right):
if type(img_cache) == daskarr:
return ext_sequential_update(mps,_imgs,img_cache,site,going_right)
if going_right:
left_cache = img_cache[:,0,site]
left_imgs = _imgs[:,site]
new_cache = tneinsum3(left_cache,np.array(len(_imgs)*[mps[site]]),left_imgs)
data = into_data(new_cache)
axes = tuple(range(1,len(data.shape)))
maxa = np.abs(data).max(axis = axes)
data = data/maxa.reshape((len(_imgs),1))
new_cache = into_tensarr(data,new_cache[0].inds)
img_cache[:,0,site+1] = new_cache
else:
right_cache = img_cache[:,1,site+1]
right_imgs = _imgs[:,site+1]
new_cache = tneinsum3(right_cache,np.array(len(_imgs)*[mps[site+1]]),right_imgs)
data = into_data(new_cache)
axes = tuple(range(1,len(data.shape)))
maxa = np.abs(data).max(axis = axes)
data = data/maxa.reshape((len(_imgs),1))
new_cache = into_tensarr(data,new_cache[0].inds)
img_cache[:,1,site] = new_cache
def ext_sequential_update(mps,_imgs,img_cache,site,going_right):
if going_right:
left_cache = img_cache[:,0,site].compute()
left_imgs = _imgs[:,site]
new_cache = tneinsum3(left_cache,np.array(len(_imgs)*[mps[site]]),left_imgs)
img_cache[:,0,site+1] = new_cache
else:
right_cache = img_cache[:,1,site+1].compute()
right_imgs = _imgs[:,site+1]
new_cache = tneinsum3(right_cache,np.array(len(_imgs)*[mps[site+1]]),right_imgs)
img_cache[:,1,site] = new_cache
def restart_cache(mps,site,left_cache,right_cache,_img):
left_site = site
right_site = site + 1
left_cache[:site+1] = extend_cache(mps,qtn.Tensor(),_img,0,left_site)
right_cache[site+1:] = np.flip(extend_cache(mps,qtn.Tensor(),_img,len(_img)-1,right_site))
return left_cache,right_cache
def advance_cache(mps,left_cache,right_cache,going_right,curr_site,last_site,_img):
if going_right:
state = left_cache[last_site]
left_cache[last_site:curr_site+1] = extend_cache(mps,state,_img,last_site,curr_site)
else:
state = right_cache[last_site+1]
right_cache[curr_site+1:last_site+2] = np.flip(extend_cache(mps,state,_img,last_site+1,curr_site+1))
return left_cache, right_cache
def extend_cache(mps,base,_img,start,end):
out = [base]
step = int(end>=start)-int(end<start)
guide = np.arange(start,end,step)
for index in guide:
A, qubit = mps[index],_img[index]
# First, contract the state, then the qubit
# TODO: is qtn.tensor_contract(out[-1],A,qubit) faster?
out.append(tneinsum2(tneinsum2(out[-1],A),qubit))
return out # Verify sorting
def half_cache(mps,right_cache,left_cache,last_site,curr_site,going_right,_img):
'''
Applied when we were going in the opposite direction half an epoch ago.
Restarts one cache, and extend the other if required
'''
if going_right:
# This means we were going left last time, therefore we have to recreate the whole left cache
left_cache[:curr_site+1] = extend_cache(mps,qtn.Tensor(),_img,0,curr_site)
if curr_site < last_site:
state = right_cache[last_site+1]
right_cache[curr_site+1:last_site+2] = np.flip(extend_cache(mps,state,_img,last_site+1,curr_site+1))
else:
# We were going right and are now going left. Restart right cache
right_cache[curr_site+1:] = np.flip(extend_cache(mps,qtn.Tensor(),_img,len(_img)-1,curr_site+1))
if curr_site > last_site:
state = left_cache[last_site]
left_cache[last_site:curr_site+1] = extend_cache(mps,state,_img,last_site,curr_site)
return left_cache, right_cache
def stochastic_cache_update(mps,_imgs,img_cache,last_dirs,last_sites,last_epochs,mask,going_right,curr_epoch,curr_site):
'''
each last_x array is a size len(img_cache) array which specifies x for the last update of the image at the given position
last_dir: specifices the direction we were heading when we last updated each image cache
last_site: specifies the last index site for which we updated the image cache
last_epoch: specifies the epoch during which we last updated the image cache
mask: mask array of images whose cache we wish to use.
'''
for index in mask:
_img = _imgs[index]
left_cache, right_cache = img_cache[index]
last_epoch = last_epochs[index]
went_right = last_dirs[index]
last_site = last_sites[index]
if curr_epoch > last_epoch:#(curr_epoch assumed to be >= last_epoch)
if last_epoch == -1:
left_cache, right_cache = restart_cache(mps, curr_site, left_cache, right_cache, _img)
elif (curr_epoch == last_epoch + 1) and (going_right>went_right):
# (It is assumed that the first stage is going right, and the second, going left)
# If we are in the first stage of the current epoch,
# and we were at the second stage of the last one,
# we build the left cache from the initial site,
# and correspondingly rescale the right cache, which is still useful.
left_cache, right_cache = half_cache(mps,right_cache,left_cache,last_site,curr_site,going_right,_img)
else:
# In this scenario, we must recreate everything
left_cache, right_cache = restart_cache(mps, curr_site, left_cache, right_cache, _img)
elif going_right<went_right:
# (we cannot be in the same epoch and going right if last time we were going left)
# We're then in the same epoch
# if we're now going left and were going right, we need to create the right cache from the last site
# and correspondingly rescale the left cache, which is still useful
left_cache, right_cache = half_cache(mps,right_cache,left_cache,last_site,curr_site,going_right,_img)
else: # We're then going in the same direction as last time
# So we must grow the corresponding site and shorten the other
left_cache, right_cache = advance_cache(mps,left_cache, right_cache, going_right,curr_site,last_site,_img)
last_sites[index] = curr_site
last_epochs[index] = curr_epoch
last_dirs[index] = going_right
img_cache[index] = left_cache, right_cache
def computepsi(mps, img):
'''
Contract the MPS with the states (pixels) of a binary{0,1} image
PSI: O-...-O-O-O-...-O
| | | | |
| | | | |
IMAGE: O O O O O
Images state are created the following way:
if pixel is 0 -> state = [0,1]
if pixel is 1 -> state = [1,0]
'''
# Left most tensor
# O--
# Compute | => O--
# O
if img[0] == 0:
contraction = np.einsum('a,ba',[0,1], mps.tensors[0].data)
else:
contraction = np.einsum('a,ba',[1,0], mps.tensors[0].data)
# Remove the first and last pixels because in the MPS
# They need to be treated differently
for k, pixel in enumerate(img[1:-1]):
#
# Compute O--O-- => O--
# | |
contraction = np.einsum('a,abc',contraction, mps.tensors[k+1].data)
# O--
# Compute | => O--
# O
if pixel == 0:
contraction = np.einsum('a,ba', [0,1], contraction)
else:
contraction = np.einsum('a,ba', [1,0], contraction)
#
# Compute O--O => O
# | |
contraction = np.einsum('a,ab',contraction, mps.tensors[-1].data)
# O
# Compute | => O (SCALAR)
# O
if img[-1] == 0:
contraction = np.einsum('a,a', [0,1], contraction)
else:
contraction = np.einsum('a,a', [1,0], contraction)
return contraction
def computepsiprime(mps, img, contracted_left_index):
'''
Contract the MPS with the states (pixels) of a binary{0,1} image
PSI': O-...-O- -O-...-O
| | | |
| | | | | |
IMAGE: O O O O O O
Images state are created the following way:
if pixel is 0 -> state = [0,1]
if pixel is 1 -> state = [1,0]
'''
if contracted_left_index == 0:
##############
# RIGHT PART #
##############
# Right most tensor
# ---O
# Compute | => --O
# O
if img[-1] == 0:
contraction_dx = np.einsum('a,ba',[0,1], mps.tensors[-1].data)
else:
contraction_dx = np.einsum('a,ba',[1,0], mps.tensors[-1].data)
for k in range(len(mps.tensors)-2, contracted_left_index+1, -1):
#
# Compute --O--O => --O
# | |
contraction_dx = np.einsum('a,bac->bc',contraction_dx, mps.tensors[k].data)
# --O
# Compute | => --O
# O
if img[k] == 0:
contraction_dx = np.einsum('a,ba', [0,1], contraction_dx)
else:
contraction_dx = np.einsum('a,ba', [1,0], contraction_dx)
# From here on it is just speculation
if img[contracted_left_index] == 0:
v0 = [0,1]
else:
v0 = [1,0]
if img[contracted_left_index+1] == 0:
contraction_dx = np.einsum('a,k->ak', contraction_dx, [0,1])
else:
contraction_dx = np.einsum('a,k->ak', contraction_dx, [1,0])
contraction = np.einsum('a,cd->acd', v0, contraction_dx)
return contraction
elif contracted_left_index == len(mps.tensors) - 2:
#############
# LEFT PART #
#############
# Left most tensor
# O--
# Compute | => O--
# O
if img[0] == 0:
contraction_sx = np.einsum('a,ba',[0,1], mps.tensors[0].data)
else:
contraction_sx = np.einsum('a,ba',[1,0], mps.tensors[0].data)
for k in range(1, contracted_left_index):
#
# Compute O--O-- => O--
# | |
contraction_sx = np.einsum('a,abc->bc',contraction_sx, mps.tensors[k].data)
# O--
# Compute | => O--
# O
if img[k] == 0:
contraction_sx = np.einsum('a,ba', [0,1], contraction_sx)
else:
contraction_sx = np.einsum('a,ba', [1,0], contraction_sx)
# From here on it is just speculation
if img[contracted_left_index] == 0:
contraction_sx = np.einsum('a,k->ak', contraction_sx, [0,1])
else:
contraction_sx = np.einsum('a,k->ak', contraction_sx, [1,0])
if img[contracted_left_index+1] == 0:
vm1 = [0,1]
else:
vm1 = [1,0]
contraction = np.einsum('ab,c->abc', contraction_sx, vm1)
return contraction
else:
#############
# LEFT PART #
#############
# Left most tensor
# O--
# Compute | => O--
# O
if img[0] == 0:
contraction_sx = np.einsum('a,ba',[0,1], mps.tensors[0].data)
else:
contraction_sx = np.einsum('a,ba',[1,0], mps.tensors[0].data)
for k in range(1, contracted_left_index):
#
# Compute O--O-- => O--
# | |
contraction_sx = np.einsum('a,abc->bc',contraction_sx, mps.tensors[k].data)
# O--
# Compute | => O--
# O
if img[k] == 0:
contraction_sx = np.einsum('a,ba', [0,1], contraction_sx)
else:
contraction_sx = np.einsum('a,ba', [1,0], contraction_sx)
##############
# RIGHT PART #
##############
# Right most tensor
# ---O
# Compute | => --O
# O
if img[-1] == 0:
contraction_dx = np.einsum('a,ba',[0,1], mps.tensors[-1].data)
else:
contraction_dx = np.einsum('a,ba',[1,0], mps.tensors[-1].data)
for k in range(len(mps.tensors)-2, contracted_left_index+1, -1):
#
# Compute --O--O => --O
# | |
contraction_dx = np.einsum('a,bac->bc',contraction_dx, mps.tensors[k].data)
# --O
# Compute | => --O
# O
if img[k] == 0:
contraction_dx = np.einsum('a,ba', [0,1], contraction_dx)
else:
contraction_dx = np.einsum('a,ba', [1,0], contraction_dx)
# From here on it is just speculation
if img[contracted_left_index] == 0:
contraction_sx = np.einsum('a,k->ak', contraction_sx, [0,1])
else:
contraction_sx = np.einsum('a,k->ak', contraction_sx, [1,0])
if img[contracted_left_index+1] == 0:
contraction_dx = np.einsum('a,k->ak', contraction_dx, [0,1])
else:
contraction_dx = np.einsum('a,k->ak', contraction_dx, [1,0])
contraction = np.einsum('ab,cd->abcd', contraction_sx, contraction_dx)
return contraction
def psi_primed(mps,_img,index):
# quimby contraction. Currently not faster than einsum implementation
# Requires _img to be provided in a quimby friendly format
# Achievable with tens_picture
contr_L = qtn.Tensor() if index == 0 else mps[0]@_img[0]
for i in range(1,index,1):
# first, contr_Lact with the other matrix
contr_L = contr_L@mps[i]
# then, with the qubit
contr_L = contr_L@_img[i]
contr_R = qtn.Tensor() if index == len(_img)-1 else mps[-1]@_img[-1]
for i in range(len(_img)-2,index+1,-1):
contr_R = mps[i]@contr_R
contr_R = _img[i]@contr_R
psi_p = contr_L@_img[index]@_img[index+1]@contr_R
return psi_p
def computeNLL(mps, imgs, canonicalized_index = False):
'''
Computes the Negative Log Likelihood of a Tensor Network (mps)
over a set of images (imgs)
> NLL = -(1/|T|) * SUM_{v\in T} ( ln P(v) ) = -(1/|T|) * SUM_{v\in T} ( ln psi(v)**2 )
= -(2/|T|) * SUM_{v\in T} ( ln |psi(v)| )
'''
if type(canonicalized_index) == int and 0<= canonicalized_index and canonicalized_index <= len(mps.tensors):
Z = tneinsum2(mps.tensors[canonicalized_index], mps.tensors[canonicalized_index]).data
else:
Z = mps @ mps
lnsum = 0
for img in imgs:
lnsum = lnsum + np.log( abs(computepsi(mps,img)) )
return - 2 * (lnsum / imgs.shape[0]) + np.log(Z)
def computeNLL_cached(mps, _imgs, img_cache, index):
A = qtn.tensor_contract(mps[index],mps[index+1])
Z = qtn.tensor_contract(A,A)
psi_primed_arr =arr_psi_primed_cache(_imgs,img_cache,index)
psi = tneinsum3(np.array(len(_imgs)*[A]),psi_primed_arr)
logpsi = np.log(np.abs(into_data(psi)))
sum_log = logpsi.sum()
# __ _ _ __ _ _ _ _
# NLL = - _1_ \ ln| _P(V)_ | = -_1_ \ | ln| |Psi(v)|^2 | - lnZ |
# |T| /_ |_ Z _| |T| /_ |_ |_ _| _|
# _ __ _ __
# = -_1_ | 2 \ ln|Psi(v)| - |T|lnZ | = -_2_ \ ln|Psi(v)| - lnZ
# |T| |_ /_ _| |T| /_
return -(2/len(_imgs))*sum_log + np.log(Z)
def computeNLL_torched(mps,imgs,torch_mps,torch_imgs,inds_dict):
# ! It is assumed that the the mps is right canonized
mps_inds = inds_dict['mps'][0]
inds_in = [mps_inds,mps_inds]
_Z,_ = torch_contract(tuple(inds_in),torch_mps[0],torch_mps[0])
Z = _Z.cpu().detach().numpy()
_inds_dict = copy.copy(inds_dict)
psi, _ = torchized_cache(torch_mps,torch_imgs,_inds_dict,True)
if 0 in psi:
# Sometimes the accuracy is too limited...
# Fallback to computeNLL
del Z, psi
print(f'Unable to compute NLL with torch variables')
return computeNLL(mps,imgs)
_psi = psi.cpu().detach().numpy()
sum_log = np.sum(np.log(np.abs(_psi)))
size = torch_imgs[0].shape[0]
nll = -2*sum_log/size + np.log(Z)
del _psi,_Z
return nll
def compress(mps, max_bond):
for index in range(len(mps.tensors)-2,-1,-1):
A = qtn.tensor_contract(mps[index],mps[index+1])
if index == 0:
SD = A.split(['v'+str(index)], absorb='left', max_bond = max_bond)
else:
SD = A.split(['i'+str(index-1),'v'+str(index)], absorb='left',max_bond = max_bond)
if index == 0:
mps.tensors[index].modify(data=np.transpose(SD.tensors[0].data,(1,0)))
mps.tensors[index+1].modify(data=SD.tensors[1].data)
else:
mps.tensors[index].modify(data=np.transpose(SD.tensors[0].data,(0,2,1)))
mps.tensors[index+1].modify(data=SD.tensors[1].data)
return mps
def compress_copy(mps, max_bond):
comp_mps = copy.copy(mps)
for index in range(len(comp_mps.tensors)-2,-1,-1):
A = qtn.tensor_contract(comp_mps[index],comp_mps[index+1])
if index == 0:
SD = A.split(['v'+str(index)], absorb='left', max_bond = max_bond)
else:
SD = A.split(['i'+str(index-1),'v'+str(index)], absorb='left',max_bond = max_bond)
if index == 0:
comp_mps.tensors[index].modify(data=np.transpose(SD.tensors[0].data,(1,0)))
comp_mps.tensors[index+1].modify(data=SD.tensors[1].data)
else:
comp_mps.tensors[index].modify(data=np.transpose(SD.tensors[0].data,(0,2,1)))
comp_mps.tensors[index+1].modify(data=SD.tensors[1].data)
return comp_mps
def compress2(mps, max_bond):
'''
unlike copress function, this first checks if the bond between
two tensors is higher than maxbond. If not it skips the pair.
THIS FUNCTION BREAKS CANONIZATION but it is faster
'''
for index in range(len(mps.tensors)-2,-1,-1):
if mps.bond_sizes()[index] > max_bond:
A = qtn.tensor_contract(mps[index],mps[index+1])
if index == 0:
SD = A.split(['v'+str(index)], absorb='left', max_bond = max_bond)
mps.tensors[index].modify(data=np.transpose(SD.tensors[0].data,(1,0)))
mps.tensors[index+1].modify(data=SD.tensors[1].data)
else:
SD = A.split(['i'+str(index-1),'v'+str(index)], absorb='left',max_bond = max_bond)
mps.tensors[index].modify(data=np.transpose(SD.tensors[0].data,(0,2,1)))
mps.tensors[index+1].modify(data=SD.tensors[1].data)
else:
pass
return mps
def torchized_mps(mps,inds_dict):
'''
Expects a quimb tensor network and a dictionary to place the indeces.
Returns an array with torch tensors for each of the mps sites.
'''
torch_mps = np.empty(len(mps.tensors),dtype = torch.Tensor)