-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsampling.py
More file actions
1081 lines (846 loc) · 42.8 KB
/
sampling.py
File metadata and controls
1081 lines (846 loc) · 42.8 KB
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
from scipy import integrate
import torch
import numpy as np
from tqdm import notebook
from torch.distributions import MultivariateNormal
from torch.distributions import Normal
import math
def Euler_Maruyama_sampler_2D(score_model,
marginal_prob_std,
diffusion_coeff,
batch_size=1000,
num_steps=1000,
device='cpu',
eps=1e-3):
t = torch.ones(batch_size, device=device)
init_x = torch.randn(batch_size, 2, device=device) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps, device=device)
step_size = time_steps[0] - time_steps[1]
x = init_x
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size, device=device) * time_step
g = diffusion_coeff(batch_time_step)
batch_time_step = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step])
mean_x = x + (g**2)[:, None] * score_model(x_with_t) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None] * torch.randn_like(x)
return mean_x
signal_to_noise_ratio = 0.16
def pc_sampler_2D(score_model,
marginal_prob_std,
diffusion_coeff,
batch_size=2048,
num_steps=1000,
snr=signal_to_noise_ratio,
device='cpu',
eps=1e-3):
t = torch.ones(batch_size, device=device)
init_x = torch.randn(batch_size, 2, device=device) * marginal_prob_std(t)[:, None]
time_steps = np.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
x = init_x
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size, device=device) * time_step
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step_])
# Corrector step (Langevin MCMC)
grad = score_model(x_with_t)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
x_with_t = torch.hstack([x, batch_time_step_])
# Predictor step (Euler-Maruyama)
g = diffusion_coeff(batch_time_step)
x_mean = x + (g**2)[:, None] * score_model(x_with_t) * step_size
x = x_mean + torch.sqrt(g**2 * step_size)[:, None] * torch.randn_like(x)
return x_mean
def CDE_Euler_Maruyama_sampler_2D(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=10000,
num_steps=1000,
eps=1e-3):
t = torch.ones(batch_size)
x = torch.randn(batch_size, 1) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
y_obs = y_obs.repeat(batch_size)
y_obs = y_obs.reshape(batch_size,1)
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size) * time_step
g = diffusion_coeff(batch_time_step)[:, None]
score = score_model(x, y_obs, batch_time_step[:,None])
mean_x = x + g**2 * score * step_size
x = mean_x + torch.sqrt(step_size) * g * torch.randn_like(x)
return mean_x
def CDE_pc_sampler_2D(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=10000,
num_steps=1000,
eps=1e-3, snr=0.16):
t = torch.ones(batch_size)
x = torch.randn(batch_size, 1) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
y_obs = y_obs.repeat(batch_size)
y_obs = y_obs.reshape(batch_size,1)
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size) * time_step
g = diffusion_coeff(batch_time_step)[:, None]
grad = score_model(x, y_obs, batch_time_step[:,None])
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
score = score_model(x, y_obs, batch_time_step[:,None])
mean_x = x + g**2 * score * step_size
x = mean_x + torch.sqrt(step_size) * g * torch.randn_like(x)
return mean_x
sigma_min=0.01
sigma_max_2D=8
sigma_max_BOD=13
sigma_max_MNIST=25
def sde_VE(x, t, sigma_min, sigma_max):
sigma = sigma_min * (sigma_max / sigma_min) ** t
diffusion = sigma * np.sqrt(2 * (np.log(sigma_max) - np.log(sigma_min)))
drift = 0
return drift, diffusion
def get_diffused_2D(data, n, sde, sigma_min, sigma_max):
data = data.clone().detach()
data = data.item()
t = 1e-5
dt = 1/n
diffused = [data]
for i in range(n):
drift, diffusion = sde(data, t, sigma_min, sigma_max)
data += drift * dt
data += diffusion * np.random.randn(1)[0] * np.sqrt(dt)
t += dt
diffused.append(data.copy())
return torch.tensor(diffused, dtype = torch.float32)[:,None]
def CDiffE_Euler_Maruyama_sampler_2D(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=10000,
num_steps=1000,
eps=1e-3,
sigma_min = sigma_min,
sigma_max = sigma_max_2D,
diffused_y = None):
t = torch.ones(batch_size)
init_x = torch.randn(batch_size, 2) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
x = init_x
if diffused_y is None:
diffused_y = [i.repeat(batch_size).reshape(batch_size,1) for i in \
get_diffused_2D(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
else:
diffused_y = [i.repeat(batch_size).reshape(batch_size,1) for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
batch_time_step = torch.ones(batch_size) * time_step
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
x = torch.hstack([x,y_obs_t])[:, [0,2]]
g = diffusion_coeff(batch_time_step)
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step_])
mean_x = x + (g**2)[:, None] * score_model(x_with_t) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None] * torch.randn_like(x)
return mean_x
def CDiffE_pc_sampler_2D(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=2048,
num_steps=1000,
snr=signal_to_noise_ratio,
eps=1e-3,
sigma_min = sigma_min,
sigma_max = sigma_max_2D):
t = torch.ones(batch_size)
init_x = torch.randn(batch_size, 2) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
x = init_x
diffused_y = [i.repeat(batch_size).reshape(batch_size,1) for i in \
get_diffused_2D(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
batch_time_step = torch.ones(batch_size) * time_step
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x = torch.hstack([x,y_obs_t])[:, [0,2]]
x_with_t = torch.hstack([x, batch_time_step_])
# Corrector step (Langevin MCMC)
grad = score_model(x_with_t)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
x_with_t = torch.hstack([x, batch_time_step_])
# Predictor step (Euler-Maruyama)
g = diffusion_coeff(batch_time_step)
x_mean = x + (g**2)[:, None] * score_model(x_with_t) * step_size
x = x_mean + torch.sqrt(g**2 * step_size)[:, None] * torch.randn_like(x)
# The last step does not include any noise
return x_mean
def SMCDiff_pc_sampler_2D(score_model, marginal_prob_std, diffusion_coeff, y_obs, k, snr=signal_to_noise_ratio,
num_steps=1000, eps=1e-3, sigma_min = sigma_min, sigma_max = sigma_max_2D):
t = torch.ones(k)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
weights = np.ones(k)/k
xs = []
init_x = torch.randn(k, 2) * marginal_prob_std(t)[:, None]
xs.append(init_x)
diffused_y = [i.repeat(k).reshape(k,1) for i in \
get_diffused_2D(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
batch_time_step = torch.ones(k) * time_step
y_obs_t = diffused_y[idx]
x = xs[-1]
x = torch.hstack([x,y_obs_t])[:, [0,2]]
if (idx - 1) >= 0:
y_update_mean, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
y_update_mean = y_update_mean[:,1]
y_update_actual = diffused_y[idx-1].flatten()
log_w = log_normal_density_2D(y_update_actual, y_update_mean, sd.flatten())
log_w -= torch.logsumexp(log_w, 0)
weights = torch.exp(log_w).cpu().detach().numpy()
weights /= sum(weights)
departure_from_uniform = np.sum(abs(k*weights-1))
if departure_from_uniform > 0.75*k:
print(idx, "resampling, departure=%0.02f"%departure_from_uniform)
resample_index = systematic(weights, k)
x = x[resample_index]
weights = np.ones_like(weights)
#corrector step (Langevin MCMC)
batch_time_step = torch.reshape(torch.ones(k) * time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step])
grad = score_model(x_with_t)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
x = torch.hstack([x,y_obs_t])[:, [0,2]]
mu, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
x_t_1 = mu + sd * torch.randn_like(x)
xs.append(x_t_1)
return xs[-1]
def SMCDiff_Euler_Maruyama_sampler_2D(score_model, marginal_prob_std, diffusion_coeff, y_obs, k, snr=signal_to_noise_ratio,
num_steps=1000, eps=1e-3, sigma_min=sigma_min, sigma_max=sigma_max_2D, diffused_y = None):
t = torch.ones(k)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
weights = np.ones(k)/k
xs = []
init_x = torch.randn(k, 2) * marginal_prob_std(t)[:, None]
xs.append(init_x)
if diffused_y is None:
diffused_y = [i.repeat(k).reshape(k,1) for i in \
get_diffused_2D(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
else:
diffused_y = [i.repeat(k).reshape(k,1) for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
batch_time_step = torch.ones(k) * time_step
y_obs_t = diffused_y[idx]
x = xs[-1]
x = torch.hstack([x,y_obs_t])[:, [0,2]]
if (idx - 1) >= 0:
y_update_mean, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
y_update_mean = y_update_mean[:,[1]]
y_update_actual = diffused_y[idx-1]#.flatten()
log_w = log_imp_weights(y_update_actual, y_update_mean, sd)
weights *= torch.exp(log_w).cpu().detach().numpy()
weights /= sum(weights)
#maybe keep, maybe get rid of, doesnt really matter for 2D
departure_from_uniform = np.sum(abs(k*weights-1))
if departure_from_uniform > 0.5*k:
print(idx, "resampling, departure=%0.02f"%departure_from_uniform)
resample_index = systematic(weights, k)
x = x[resample_index]
weights = np.ones_like(weights)/k
mu, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
x_t_1 = mu + sd * torch.randn_like(x)
xs.append(x_t_1)
return xs[-1]
def log_normal_density_2D(sample, mean, sd):
return Normal(loc=mean, scale=sd).log_prob(sample)
#################
#################
#################
signal_to_noise_ratio = 0.16
def pc_sampler_BOD(score_model,
marginal_prob_std,
diffusion_coeff,
batch_size=10000,
num_steps=1000,
snr=signal_to_noise_ratio,
eps=1e-5):
t = torch.ones(batch_size)
init_x = torch.randn(batch_size, 7) * marginal_prob_std(t)[:, None]
time_steps = np.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
x = init_x
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size) * time_step
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step_])
# Corrector step (Langevin MCMC)
grad = score_model(x_with_t)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
# Predictor step (Euler-Maruyama)
mu, sd = get_next_x(x, batch_size, score_model, diffusion_coeff, time_step, torch.tensor(step_size))
x = mu + sd * torch.randn_like(x)
return mu
def Euler_Maruyama_sampler_BOD(score_model,
marginal_prob_std,
diffusion_coeff,
batch_size=10000,
num_steps=1000,
eps=1e-5):
t = torch.ones(batch_size)
init_x = torch.randn(batch_size, 7) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
x = init_x
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size) * time_step
g = diffusion_coeff(batch_time_step)
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step_])
score = score_model(x_with_t)
mean_x = x + (g**2)[:, None] * score * step_size
sd = torch.sqrt(step_size) * g[:, None]
mu, sd = get_next_x(x, batch_size, score_model, diffusion_coeff, time_step, step_size)
x = mu + sd * torch.randn_like(x)
return mu
def get_next_x(x, batch_size, score_model, diffusion_coeff, time_step, step_size):
batch_time_step = torch.ones(batch_size) * time_step
g = diffusion_coeff(batch_time_step)
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step_])
score = score_model(x_with_t)
mean_x = x + (g**2)[:, None] * score * step_size
sd = torch.sqrt(step_size) * g[:, None]
return mean_x, sd
def get_diffused_BOD(obs, n, sde, sigma_min, sigma_max):
data = obs.clone().detach()
t = 1e-5
dt = 1/n
diffused = [data.clone().detach()]
for i in range(n):
drift, diffusion = sde(data, t, sigma_min, sigma_max)
data += drift * dt
data += diffusion * torch.randn(5) * np.sqrt(dt)
diffused.append(data.clone().detach())
t += dt
return torch.vstack(diffused)
def CDiffE_Euler_Maruyama_sampler_BOD(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=10000,
num_steps=1000,
eps=1e-5, sigma_min=sigma_min, sigma_max=sigma_max_BOD, diffused_y=None):
t = torch.ones(batch_size)
x = torch.randn(batch_size, 7) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
if diffused_y is None:
diffused_y = [i.repeat(batch_size).reshape(batch_size,5) for i in \
get_diffused_BOD(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
else:
diffused_y = [i.repeat(batch_size).reshape(batch_size,5) for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
x = torch.hstack([x,y_obs_t])[:, [0,1,7,8,9,10,11]]
mu, sd = get_next_x(x, batch_size, score_model, diffusion_coeff, time_step, step_size)
x = mu + sd * torch.randn_like(x)
return mu
signal_to_noise_ratio = 0.16
def CDiffE_pc_sampler_BOD(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=2048,
num_steps=1000,
snr=signal_to_noise_ratio,
eps=1e-5, sigma_min=sigma_min, sigma_max=sigma_max_BOD, diffused_y=None):
t = torch.ones(batch_size)
init_x = torch.randn(batch_size, 7) * marginal_prob_std(t)[:, None]
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
x = init_x
if diffused_y is None:
diffused_y = [i.repeat(batch_size).reshape(batch_size,5) for i in \
get_diffused_BOD(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
else:
diffused_y = [i.repeat(batch_size).reshape(batch_size,5) for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
x = torch.hstack([x,y_obs_t])[:, [0,1,7,8,9,10,11]]
# Corrector step (Langevin MCMC)
batch_time_step = torch.reshape(torch.ones(batch_size) * time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step])
grad = score_model(x_with_t)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
x = torch.hstack([x,y_obs_t])[:, [0,1,7,8,9,10,11]]
# Predictor step (Euler-Maruyama)
mu, sd = get_next_x(x, batch_size, score_model, diffusion_coeff, time_step, step_size)
x = mu + sd * torch.randn_like(x)
return mu
def CDE_Euler_Maruyama_sampler_BOD(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=2048,
num_steps=1000,
eps=1e-5):
t = torch.ones(batch_size)
init_x = torch.randn(batch_size, 2) * marginal_prob_std(t)[:, None]
time_steps = np.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
y_obs = y_obs.repeat(batch_size)
y_obs = y_obs.reshape(batch_size,5)
x = torch.hstack([init_x, y_obs])
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
# Predictor step
x = cde_get_next_x(x, y_obs, batch_size, score_model, diffusion_coeff, time_step, torch.tensor(step_size))
return x
def CDE_pc_sampler_BOD(score_model,
marginal_prob_std,
diffusion_coeff,
y_obs,
batch_size=2048,
num_steps=1000,
snr=signal_to_noise_ratio,
eps=1e-5):
t = torch.ones(batch_size)
init_x = torch.randn(batch_size, 2) * marginal_prob_std(t)[:, None]
time_steps = np.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
y_obs = y_obs.repeat(batch_size)
y_obs = y_obs.reshape(batch_size,5)
x = torch.hstack([init_x, y_obs])
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size) * time_step
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step_])
# Corrector step (Langevin MCMC)
grad = score_model(x_with_t)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x[:,[0,1]]
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
x = torch.hstack([x, y_obs])
# Predictor step
x = cde_get_next_x(x, y_obs, batch_size, score_model, diffusion_coeff, time_step, torch.tensor(step_size))
return x
def cde_get_next_x(x, y_obs, batch_size, score_model, diffusion_coeff, time_step, step_size):
batch_time_step = torch.ones(batch_size) * time_step
g = diffusion_coeff(batch_time_step)
batch_time_step_ = torch.reshape(batch_time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step_])
score = score_model(x_with_t)
x = x[:,[0,1]]
mean_x = x + (g**2)[:, None] * score * step_size
sd = torch.sqrt(step_size) * g[:, None]
x = mean_x + sd * torch.randn_like(x)
x = torch.hstack([x, y_obs])
return x
def log_imp_weights(sample, mean, sd):
log_w = -(1./2)*(sample-mean)**2/(sd**2)
log_w = torch.sum(log_w, axis=[1])
log_w -= torch.logsumexp(log_w, 0)
return log_w
def SMCDiff_Euler_Maruyama_sampler_BOD(score_model, marginal_prob_std, diffusion_coeff, y_obs, k, num_steps=1000,
eps=1e-5, snr=signal_to_noise_ratio, sigma_min=sigma_min, sigma_max=sigma_max_BOD, diffused_y=None):
t = torch.ones(k)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
weights = np.ones(k)/k
xs = []
init_x = torch.randn(k, 7) * marginal_prob_std(t)[:, None]
xs.append(init_x)
if diffused_y is None:
diffused_y = [i.repeat(k).reshape(k,5) for i in get_diffused_BOD(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
else:
diffused_y = [i.repeat(k).reshape(k,5) for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
batch_time_step = torch.ones(k) * time_step
y_obs_t = diffused_y[idx]
x = xs[-1]
x = torch.hstack([x,y_obs_t])[:, [0,1,7,8,9,10,11]]
#get predicted y_{t-1}
if (idx - 1) >= 0:
y_update_mean, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
y_update_mean = y_update_mean[:,[2,3,4,5,6]]
y_update_actual = diffused_y[idx-1]
log_w = log_imp_weights(y_update_actual, y_update_mean, sd)
weights *= torch.exp(log_w).cpu().detach().numpy()
weights /= sum(weights)
departure_from_uniform = np.sum(abs(k*weights-1))
if departure_from_uniform > 0.5*k:
#print(idx, "resampling, departure=%0.02f"%departure_from_uniform)
resample_index = systematic(weights, k)
x = x[resample_index]
weights = np.ones_like(weights)/k
mu, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
x_t_1 = mu + sd * torch.randn_like(x)
xs.append(x_t_1)
return xs[-1]
def SMCDiff_pc_sampler_BOD(score_model, marginal_prob_std, diffusion_coeff, y_obs, k, num_steps=1000,
eps=1e-5, snr=signal_to_noise_ratio, sigma_min=sigma_min, sigma_max=sigma_max_BOD, diffused_y=None):
t = torch.ones(k)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
weights = np.ones(k)/k
xs = []
init_x = torch.randn(k, 7) * marginal_prob_std(t)[:, None]
xs.append(init_x)
if diffused_y is None:
diffused_y = [i.repeat(k).reshape(k,5) for i in get_diffused_BOD(y_obs, num_steps, sde_VE, sigma_min, sigma_max)]
else:
diffused_y = [i.repeat(k).reshape(k,5) for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
batch_time_step = torch.ones(k) * time_step
y_obs_t = diffused_y[idx]
x = xs[-1]
x = torch.hstack([x,y_obs_t])[:, [0,1,7,8,9,10,11]]
#corrector step (Langevin MCMC)
batch_time_step = torch.reshape(torch.ones(k) * time_step, (x.shape[0], 1))
x_with_t = torch.hstack([x, batch_time_step])
grad = score_model(x_with_t)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
x = torch.hstack([x,y_obs_t])[:, [0,1,7,8,9,10,11]]
#get predicted y_{t-1}
if (idx - 1) >= 0:
y_update_mean, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
y_update_mean = y_update_mean[:,[2,3,4,5,6]]
y_update_actual = diffused_y[idx-1]
# compute un-normalized weighting factor for importance resampling step
log_w = log_normal_density(y_update_actual, y_update_mean, sd)
log_w -= torch.logsumexp(log_w, 0)
# Update Self-normalized importance weights
weights *= torch.exp(log_w).cpu().detach().numpy()
weights /= sum(weights) # Re-normalize
departure_from_uniform = np.sum(abs(k*weights-1))
if departure_from_uniform > 0.5*k:
#print(idx, "resampling, departure=%0.02f"%departure_from_uniform)
resample_index = systematic(weights, k)
x = x[resample_index]
weights = np.ones_like(weights)/k
mu, sd = get_next_x(x, k, score_model, diffusion_coeff, time_step, step_size)
x_t_1 = mu + sd * torch.randn_like(x)
xs.append(x_t_1)
return xs[-1]
def residual(W):
N = W.shape[0]
M = N
A = np.empty(M, dtype=np.int64)
MW = M * W
intpart = np.floor(MW).astype(np.int64)
sip = np.sum(intpart)
res = MW - intpart
sres = M - sip
A[:sip] = np.arange(N).repeat(intpart)
# each particle n is repeated intpart[n] times
if sres > 0:
A[sip:] = multinomial(res / sres, M=sres)
return A
def systematic(W, M):
su = (np.random.rand(1) + np.arange(M)) / M
return inverse_cdf(su, W)
def multinomial(W, M):
return inverse_cdf(uniform_spacings(M), W)
def uniform_spacings(N):
z = np.cumsum(-np.log(np.random.rand(N + 1)))
return z[:-1] / z[-1]
def inverse_cdf(su, W):
j = 0
s = W[0]
M = su.shape[0]
A = np.empty(M, dtype=np.int64)
for n in range(M):
while su[n] > s:
if j < W.shape[0]-1:
j += 1
s += W[j]
A[n] = j
return A
#################
#################
#################
def Euler_Maruyama_sampler_MNIST(score_model, marginal_prob_std, diffusion_coeff,
batch_size=64, num_steps=1000, device='cpu', eps=1e-3):
t = torch.ones(batch_size, device=device)
init_x = torch.randn(batch_size, 1, 28, 28, device=device) * marginal_prob_std(t)[:, None, None, None]
time_steps = torch.linspace(1., eps, num_steps, device=device)
step_size = time_steps[0] - time_steps[1]
x = init_x
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size, device=device) * time_step
g = diffusion_coeff(batch_time_step)
mean_x = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None, None, None] * torch.randn_like(x)
return mean_x
def pc_sampler_MNIST(score_model, marginal_prob_std, diffusion_coeff,
batch_size=64, num_steps=1000, snr=0.16, device='cpu', eps=1e-3):
t = torch.ones(batch_size, device=device)
init_x = torch.randn(batch_size, 1, 28, 28, device=device) * marginal_prob_std(t)[:, None, None, None]
time_steps = np.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
x = init_x
with torch.no_grad():
for time_step in notebook.tqdm(time_steps):
batch_time_step = torch.ones(batch_size, device=device) * time_step
# Corrector step (Langevin MCMC)
grad = score_model(x, batch_time_step)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
# Predictor step (Euler-Maruyama)
g = diffusion_coeff(batch_time_step)
x_mean = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step) * step_size
x = x_mean + torch.sqrt(g**2 * step_size)[:, None, None, None] * torch.randn_like(x)
return x_mean
def get_diffused_MNIST(obs, n, sde, sigma_min=0.01, sigma_max=25):
data = obs.clone().detach()
t = 1e-5
dt = 1/n
diffused = [data.clone().detach()]
for i in range(n):
drift, diffusion = sde(data, t, sigma_min, sigma_max)
data += drift * dt
data += diffusion * torch.randn(28,28, device=device) * np.sqrt(dt)
diffused.append(data.clone().detach())
t += dt
return torch.stack(diffused)
def insert_condition(x, y_obs):
inserted = x.clone().detach()
for i in inserted:
i[0][:, :14] = y_obs
return inserted
device='cpu'
def CDiffE_Euler_Maruyama_sampler_MNIST(score_model, marginal_prob_std, diffusion_coeff, y_obs, batch_size=16, num_steps=1000,
eps=1e-3, sigma_min=sigma_min, sigma_max=sigma_max_MNIST, diffused_y=None):
t = torch.ones(batch_size, device=device)
x = torch.randn(batch_size, 1, 28, 28, device=device) * marginal_prob_std(1)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
if diffused_y is None:
diffused_y = get_diffused_MNIST(y_obs, 1000, sde_VE, sigma_min, sigma_max)
diffused_y = [i[:,:14] for i in diffused_y]
else:
diffused_y = [i[:,:14] for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
x = insert_condition(x, y_obs_t)
batch_time_step = torch.ones(batch_size, device=device) * time_step
g = diffusion_coeff(batch_time_step)
mean_x = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None, None, None] * torch.randn_like(x)
return mean_x
def CDiffE_pc_sampler_MNIST(score_model, marginal_prob_std, diffusion_coeff, y_obs, batch_size=16, num_steps=1000,
eps=1e-3, sigma_min=sigma_min, sigma_max=sigma_max_MNIST, diffused_y=None, snr=0.16):
t = torch.ones(batch_size, device=device)
x = torch.randn(batch_size, 1, 28, 28, device=device) * marginal_prob_std(1)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
if diffused_y is None:
diffused_y = get_diffused_MNIST(y_obs, 1000, sde_VE, sigma_min, sigma_max)
diffused_y = [i[:,:14] for i in diffused_y]
else:
diffused_y = [i[:,:14] for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
x = insert_condition(x, y_obs_t)
batch_time_step = torch.ones(batch_size) * time_step
# Corrector step (Langevin MCMC)
grad = score_model(x, batch_time_step)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(x.shape[1:]))
langevin_step_size = 2 * (snr * noise_norm / grad_norm)**2
x = x + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(x)
x = insert_condition(x, y_obs_t)
# Predictor step
g = diffusion_coeff(batch_time_step)
mean_x = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None, None, None] * torch.randn_like(x)
return mean_x
def get_y(x, k):
y = torch.zeros(k,1,28,14)
for i in range(k):
y[i][0] = x[i][0][:, :14]
return y
def log_imp_weights_MNIST(sample, mean, sd):
log_w = -(1./2)*(sample-mean)**2/(sd**2)
log_w = torch.sum(log_w, axis=[1,2,3])
log_w -= torch.logsumexp(log_w, 0)
return log_w
def SMCDiff_Euler_Maruyama_sampler_MNIST(score_model, marginal_prob_std, diffusion_coeff, y_obs, k, num_steps=1000,
eps=1e-3, sigma_min=sigma_min, sigma_max=sigma_max_MNIST, diffused_y=None):
t = torch.ones(k, device=device)
x = torch.randn(k, 1, 28, 28, device=device) * marginal_prob_std(1)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
weights = np.ones(k)/k
if diffused_y is None:
diffused_y = get_diffused_MNIST(y_obs, 1000, sde_VE, sigma_min, sigma_max)
diffused_y = [i[:,:14] for i in diffused_y]
else:
diffused_y = [i[:,:14] for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
x = insert_condition(x, y_obs_t)
batch_time_step = torch.ones(k, device=device) * time_step
g = diffusion_coeff(batch_time_step)
if (idx - 1) >= 0:
mean_x = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step) * step_size
sd = torch.sqrt(step_size) * g[:, None, None, None]
y_update_mean = get_y(mean_x, k)
y_update_actual = diffused_y[idx-1]
log_w = log_imp_weights_MNIST(y_update_actual, y_update_mean, sd)
weights *= torch.exp(log_w).cpu().detach().numpy()
weights /= sum(weights)
departure_from_uniform = np.sum(abs(k*weights-1))
if (departure_from_uniform > 0.75*k) and (idx>50):
#print(idx, "resampling, departure=%0.02f"%departure_from_uniform)
resample_index = systematic(weights, k)
x = x[resample_index]
weights = np.ones_like(weights)/k
mean_x = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None, None, None] * torch.randn_like(x)
return mean_x
def SMCDiff_pc_sampler_MNIST(score_model, marginal_prob_std, diffusion_coeff, y_obs, k, num_steps=1000,
eps=1e-3, sigma_min=sigma_min, sigma_max=sigma_max_MNIST, diffused_y=None, snr=0.16):
t = torch.ones(k, device=device)
x = torch.randn(k, 1, 28, 28, device=device) * marginal_prob_std(1)
time_steps = torch.linspace(1., eps, num_steps)
step_size = time_steps[0] - time_steps[1]
weights = np.ones(k)/k
if diffused_y is None:
diffused_y = get_diffused_MNIST(y_obs, 1000, sde_VE, sigma_min, sigma_max)
diffused_y = [i[:,:14] for i in diffused_y]
else:
diffused_y = [i[:,:14] for i in diffused_y]
with torch.no_grad():
for idx, time_step in enumerate(notebook.tqdm(time_steps)):
idx = num_steps - idx - 1
y_obs_t = diffused_y[idx]
x = insert_condition(x, y_obs_t)
batch_time_step = torch.ones(k, device=device) * time_step
g = diffusion_coeff(batch_time_step)
# SMC step
if (idx - 1) >= 0:
mean_x = x + (g**2)[:, None, None, None] * score_model(x, batch_time_step) * step_size
sd = torch.sqrt(step_size) * g[:, None, None, None]
y_update_mean = get_y(mean_x, k)