-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoy_example.py
More file actions
1258 lines (1026 loc) · 53.2 KB
/
toy_example.py
File metadata and controls
1258 lines (1026 loc) · 53.2 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
"""2D toy example from the paper : Memorization to Generalization: Diffusion Models from Dense Associative Memory"""
import os
import math
import torch
import click
from tqdm import tqdm
import numpy as np
import torch.nn as nn
from itertools import cycle
import matplotlib.pyplot as plt
from scipy.special import i0, i1
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import scipy.integrate as integrate
from sklearn.cluster import AgglomerativeClustering
from scipy.spatial import distance_matrix
from scipy.stats import gaussian_kde
from scipy.signal import find_peaks
import seaborn as sns
from sklearn.cluster import DBSCAN
from sklearn.cluster import KMeans
sns.set_theme(style="whitegrid")
#------------------------------------------------------------------------------------------------
# Data generation. It generates data that lies on a unit circle and allows sampling a subset of data.
# The class CircleData is a wrapper around the data generation function and has the exact energy of the model
def generate_circle_data(num_samples=50000, radius=1, seed=59):
np.random.seed(seed)
angles = np.random.uniform(0, 2*np.pi, num_samples)
x = radius * np.cos(angles)
y = radius * np.sin(angles)
return np.stack([x, y], axis=1)
class CircleDataset(Dataset):
def __init__(self, num_samples=50000, radius=1, seed=9):
self.data = generate_circle_data(num_samples, radius, seed)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def cartesian_to_polar(self, samples):
x = samples[:, 0]
y = samples[:, 1]
r = np.sqrt(x**2 + y**2)
angles = np.arctan2(y, x)
return r, angles
def energy_am(self, samples, beta, normalize=True):
"""
Computes the energy function E^AM(R, phi) = R^2 + 1 - (1 / beta) * log(I_0(2 * beta * R)). Eq. (13) in the paper.
"""
r, _ = self.cartesian_to_polar(samples)
energy = r**2 + 1 - (1 / beta) * np.log(i0(2 * beta * r))
# Shift so that the lowest energy is
if normalize:
min_energy = energy.min()
energy -= min_energy
return energy
def score_am(self, samples, beta, epsilon=1e-6):
"""
Computes the score function S^AM(R, phi) = -2 * R - (2 / beta) * I_1(2 * beta * R) / I_0(2 * beta * R). Eq. (18) in the paper.
"""
r, _ = self.cartesian_to_polar(samples)
# Ensure r is not zero to avoid division by zero
r = np.clip(r, epsilon, np.inf)
bessel_ratio = i1(2 * beta * r) / i0(2 * beta * r)
score_r = 2 * (bessel_ratio - r)
score = score_r[:, None] * samples / r[:, None]
return score
#------------------------------------------------------------------------------------------------
# Data Utilities
def create_subset(dataset, sample_size, seed=42):
"""Create a subset of the dataset based on the specified sample size. """
max_size = len(dataset)
generator = torch.Generator().manual_seed(seed)
if not 1 <= sample_size <= len(dataset):
raise ValueError("Sample size must be between 1 and the size of the dataset inclusive.")
subset, _ = torch.utils.data.random_split(
dataset, [sample_size, max_size - sample_size], generator=generator
)
return subset
def prepare_datasets(sample_size, train_size=60000, test_size=10000, seed=9):
dataset = CircleDataset(num_samples=train_size, seed=seed)
test_dataset = CircleDataset(num_samples=test_size, seed=seed)
train_subset = create_subset(dataset, sample_size)
test_subset = create_subset(test_dataset, sample_size)
return train_subset, test_subset
#------------------------------------------------------------------------------------------------
# Visualization Helper Functions
def save_circle_plot(data, save_dir, filename='circle_plot.png', radius=1, figsize=(8, 8), fontsize=12, show=False):
# Generate the circle for the continuous manifold
theta = np.linspace(0, 2 * np.pi, 100)
circle_x = radius * np.cos(theta)
circle_y = radius * np.sin(theta)
# Create the plot
plt.figure(figsize=figsize)
plt.plot(circle_x, circle_y, label='Continuous Manifold (Circumference)', color='gray')
plt.scatter(data[:, 0], data[:, 1], color='red', label='Train Data (Patterns)')
plt.gca().set_aspect('equal', adjustable='box')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(fontsize=fontsize)
# Save the plot
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_path = os.path.join(save_dir, filename)
if show:
plt.show()
else:
plt.savefig(save_path, bbox_inches='tight')
plt.close()
def plot_score2DCircle(grid_tensor, samples, scores, patterns, figsize=(8, 8),
fontsize=12, save_path="./",show=False,radius=1):
# Generate the circle for the continuous manifold
theta = np.linspace(0, 2 * np.pi, 100)
circle_x = radius * np.cos(theta)
circle_y = radius * np.sin(theta)
# Plot
plt.figure(figsize=figsize)
plt.grid(False)
plt.plot(circle_x, circle_y, label='Continuous Manifold', color='blue', alpha=0.25)
plt.quiver(grid_tensor[:, 0], grid_tensor[:, 1], scores[:, 0], scores[:, 1], width=0.005)
plt.scatter(samples[:, 0].cpu(), samples[:, 1].cpu(), marker="o", s=10, label="Generated Samples")
plt.scatter(patterns[:, 0], patterns[:, 1], marker="*", s=50, color="red", label="Patterns")
plt.legend(fontsize=fontsize)
if show:
plt.show()
else:
plt.tight_layout(pad=0)
plt.savefig(save_path, bbox_inches='tight')
plt.close()
def visualize_dataset_splits(sample_sizes, seed=9, save_dir=None):
theta = np.linspace(0, 2 * np.pi, 100)
circle_x, circle_y = np.cos(theta), np.sin(theta)
fig, axes = plt.subplots(1, len(sample_sizes), figsize=(5 * len(sample_sizes), 5))
for idx, (ax, sample_size) in enumerate(zip(axes, sample_sizes)):
ax.plot(circle_x, circle_y, label='Continuous Manifold', color='k', linewidth=2, alpha=0.5)
train_subset, _ = prepare_datasets(sample_size, seed=seed)
train_data = train_subset.dataset[train_subset.indices]
ax.scatter(train_data[:, 0], train_data[:, 1], label='Train Data', s=80, alpha=0.5)
ax.set_title(f'Sample Size: {sample_size}', fontsize=16)
if idx == 0:
ax.legend()
plt.tight_layout()
if save_dir:
fig.savefig(os.path.join(save_dir, f'dataset_splits_{seed}.png'), bbox_inches='tight')
print(f"Dataset splits saved to {os.path.join(save_dir, f'dataset_splits_{seed}.png')}")
plt.show()
plt.close(fig)
def create_grid(bounds=(-1.5, 1.5), resolution=20):
x = torch.linspace(bounds[0], bounds[1], resolution)
y = torch.linspace(bounds[0], bounds[1], resolution)
X, Y = torch.meshgrid(x, y, indexing='ij')
return X, Y, torch.stack([X.flatten(), Y.flatten()], dim=1)
def plot_energy_with_scores(grid_points, energy, scores, patterns, save_path=None):
""""Assumes that the energy and scores are computed on the grid points"""
# Reshape energy and scores to match the grid points
h = int(np.sqrt(energy.shape[0]))
energy_grid = energy.reshape(h, h)
scores_grid = scores.reshape(h, h, 2)
# Generate circle outline points
circle = plt.Circle((0, 0), 1, color='black', linewidth=2, alpha=1, fill=False)
# Plot
plt.figure(figsize=(8, 6))
plt.grid(False)
# Plot energy contour
X = grid_points[:,0].reshape(h,h)
Y = grid_points[:,1].reshape(h,h)
plt.contourf(X, Y, energy_grid, levels=100, cmap='inferno')
cbar = plt.colorbar(label='Energy')
# Plot score field
plt.quiver(grid_points[:, 0], grid_points[:, 1],
scores_grid[:, :, 0], scores_grid[:, :, 1],
color='white', alpha=0.7)
# Plot circle and data points
plt.gca().add_artist(circle)
plt.scatter(patterns[:, 0], patterns[:, 1], marker="*", s=350, color="red", label="Patterns")
# Style adjustments
cbar.set_label('Energy', fontsize=35)
cbar.ax.yaxis.set_tick_params(labelsize=25)
plt.gca().set_axis_off()
plt.tight_layout(pad=0)
if save_path is not None:
plt.savefig(save_path, bbox_inches='tight', transparent=True, dpi=200)
plt.show()
def plot_energy_landscape(energy, scores, grid_tensor, samples, patterns, sample_size,
cluster_data=None, show_clusters=True, save_dir=None,
fontsize=12, t=1e-5, reversed=False, legend=False):
"""
Create a visualization of the energy landscape with samples, scores and optionally clusters.
"""
grid_points = grid_tensor.detach().cpu().numpy()
X = grid_tensor[:, 0].reshape(20, 20).detach().cpu().numpy()
Y = grid_tensor[:, 1].reshape(20, 20).detach().cpu().numpy()
grid_size = int(np.sqrt(grid_tensor.shape[0]))
# fig = plt.figure(figsize=(8, 6))
fig = plt.figure(figsize=(6, 6))
# Plot energy contour first
energy_grid = energy.reshape(grid_size, grid_size).detach().cpu().numpy()
plt.contourf(X, Y, energy_grid, levels=100, cmap='inferno')
# cbar = plt.colorbar(label='Energy')
# Plot score field
plt.quiver(grid_points[:, 0], grid_points[:, 1],
scores[:, 0], scores[:, 1],
color='white', alpha=0.7)
circle = plt.Circle((0, 0), 1, color='black', linewidth=2, alpha=1, fill=False)
plt.gca().add_artist(circle)
if show_clusters == False:
# Plot patterns
plt.scatter(patterns[:, 0], patterns[:, 1],
marker="*", color="red", s=350,
alpha=1, label="Patterns")
if show_clusters and cluster_data is not None:
cluster_centers, cluster_labels, cluster_energies = cluster_data
if not reversed:
# Plot clustered samples with improved visualization
plt.scatter(samples[:, 0].cpu(), samples[:, 1].cpu(),
c=cluster_labels, marker="o", s=50,
alpha=0.8, cmap='coolwarm',
edgecolor='black', linewidth=0.5,
label="Generated Data")
plt.scatter(patterns[:, 0], patterns[:, 1],
marker="*", color="red", s=500,
alpha=1, label="Patterns")
# Plot cluster centers with dark green color instead of yellow
plt.scatter(cluster_centers[:, 0], cluster_centers[:, 1],
marker='X', s=200, color='yellow',
alpha=1, label='Cluster Centers')
if reversed:
plt.scatter(samples[:, 0].cpu(), samples[:, 1].cpu(),
c=cluster_labels, marker="o", s=50,
alpha=0.8, cmap='coolwarm',
edgecolor='black', linewidth=0.5,
label="Generated Data")
print("Cluster centers shape: ", cluster_centers.shape)
# Add energy values as annotations near cluster centers
if len(cluster_centers) > 50:
step = len(cluster_centers) // 50
selected_centers = cluster_centers[::step]
selected_energies = cluster_energies[::step]
else:
selected_centers = cluster_centers
selected_energies = cluster_energies
for center, energy_val in zip(selected_centers, selected_energies):
plt.annotate(f'{energy_val:.2f}',
(center[0], center[1]),
xytext=(12,-2),
textcoords='offset points',
color='white',
fontsize=fontsize)
if legend:
plt.legend(fontsize=20, loc='upper right')
plt.gca().set_axis_off()
plt.tight_layout(pad=0)
if save_dir:
filename = f"2d_circle_vesde_clustering_energy_{sample_size}_t_{t:.5f}.png"
save_path = os.path.join(save_dir, filename)
plt.savefig(save_path, bbox_inches='tight', transparent=True)
plt.show()
plt.close()
#------------------------------------------------------------------------------------------------
# Model architecture. This is the score-based model used in the paper.
# to train our 2d samples.
class FourierEmbedding(torch.nn.Module):
def __init__(self, embed_dim, scale=16):
super().__init__()
self.register_buffer('freqs', torch.randn(embed_dim // 2) * scale)
def forward(self, x):
x = x.ger((2 * np.pi * self.freqs).to(x.dtype))
x = torch.cat([x.cos(), x.sin()], dim=1)
return x
class ResidualBlock(nn.Module):
def __init__(self, dim):
super().__init__()
self.net = nn.Sequential(
nn.LayerNorm(dim),
nn.ReLU(),
nn.Linear(dim, dim),
nn.LayerNorm(dim),
nn.ReLU(),
nn.Linear(dim, dim)
)
def forward(self, x):
return x + self.net(x)
class ScoreNet(nn.Module):
def __init__(
self,
input_dim=2,
num_layers=4,
hidden_dim=128,
embed_dim=128,
marginal_prob_std=None
):
super().__init__()
self.act = nn.SiLU()
self.marginal_prob_std = marginal_prob_std
# Time embedding
self.time_embed = nn.Sequential(
FourierEmbedding(embed_dim=embed_dim),
nn.Linear(embed_dim, embed_dim),
nn.SiLU(),
nn.Linear(embed_dim, embed_dim),
nn.SiLU()
)
# Project combined (x + time-embedding) to hidden dimension
self.input_proj = nn.Linear(input_dim + embed_dim, hidden_dim)
# Hidden MLP layers
layers = []
for _ in range(num_layers - 1):
layers.append(nn.Linear(hidden_dim, hidden_dim))
layers.append(nn.SiLU())
self.hidden = nn.Sequential(*layers)
# Final output to 2 dimensions
self.output = nn.Linear(hidden_dim, 2)
def forward(self, x, t):
# Generate time embedding and concatenate with x
t_emb = self.time_embed(t)
h = torch.cat([x, t_emb], dim=1)
# Pass through MLP
h = self.input_proj(h)
h = self.hidden(h)
h = self.output(h)
# Scale by 1 / marginal_prob_std(t)
return h / self.marginal_prob_std(t)[:, None]
#------------------------------------------------------------------------------------------------
# SDE Terms define the Gaussian kernel used.
class VESDETerms:
def __init__(self, sigma, device=None):
self.sigma = sigma
self.device = device
def marginal_prob_std(self, t):
t = torch.as_tensor(t, device=self.device, dtype=torch.float32)
return self.sigma * torch.sqrt(t)
def diffusion_coeff(self, t):
t = torch.as_tensor(t, device=self.device, dtype=torch.float32)
return self.sigma * torch.ones_like(t)
#------------------------------------------------------------------------------------------------
# Sampler
def Euler_Maruyama_sampler(score_model,
marginal_prob_std,
diffusion_coeff,
batch_size=64,
num_steps=1000,
device='cuda',
eps=1e-3):
"""Generate samples from score-based models with the Euler-Maruyama solver."""
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 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] * score_model(x, batch_time_step) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None] * torch.randn_like(x)
# Do not include any noise in the last sampling step.
return mean_x
#------------------------------------------------------------------------------------------------
# Training utils
def score_eval_wrapper(sample, time_steps, score_model):
"""A wrapper of the score-based model for use by the ODE solver."""
# Keep original shape for reshaping later
original_shape = sample.shape
device = sample.device
# Convert to tensor if not already
if not isinstance(sample, torch.Tensor):
sample = torch.tensor(sample, device=device, dtype=torch.float32)
sample = sample.reshape(original_shape)
if not isinstance(time_steps, torch.Tensor):
time_steps = torch.tensor(time_steps, device=device, dtype=torch.float32)
time_steps = time_steps.reshape((sample.shape[0], ))
with torch.no_grad():
score = score_model(sample, time_steps)
# Reshape score to match expected 2D shape for plotting
return score.cpu().numpy().reshape((-1, 2)).astype(np.float64)
def loss_fn(model, x, marginal_prob_std, eps=1e-5):
random_t = torch.rand(x.shape[0], device=x.device) * (1. - eps) + eps
z = torch.randn_like(x)
std = marginal_prob_std(random_t)
perturbed_x = x + z * std[:, None]
score = model(perturbed_x, random_t)
loss = torch.mean(torch.sum((score * std[:, None] + z)**2, dim=1))
return loss
def train_score_model(score_model, train_loader, test_loader, optimizer, device,
marginal_prob_std_fn, diffusion_coeff_fn, total_iterations=100000,
initial_step=0, eps=1e-12, sampling_dir=None, log_freq=100,
model_save_dir=None,
sampling_freq=1000):
dataset_name = "circle"
# Generation setup for visualization
X, Y, grid_points = create_grid(bounds=(-1.5, 1.5), resolution=20)
grid_points = np.stack([X.ravel(), Y.ravel()], axis=-1)
grid_tensor = torch.tensor(grid_points, dtype=torch.float32)
# Training monitoring variables
log_steps = 0
running_loss = 0
losses = []
eval_losses = []
print("Total iterations: ", total_iterations)
infinite_loader = iter(cycle(train_loader))
for iteration in range(initial_step, total_iterations + 1):
# Get batch
x = next(infinite_loader)
x = x.to(device).type(torch.float32)
# Compute loss
loss = loss_fn(score_model, x, marginal_prob_std_fn, eps=eps)
# Optimization step
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
log_steps += 1
losses.append(loss.item())
if iteration % log_freq == 0 and iteration > 0:
avg_loss = running_loss / log_steps
print(f"Iteration {iteration}/{total_iterations}, Avg Loss : {avg_loss:.6f}")
# Compute evaluation loss
eval_loss = 0.0
score_model.eval() # Set the model to evaluation mode for eval loss
with torch.no_grad():
for test_x in test_loader:
test_x = test_x.to(device).type(torch.float32)
eval_loss += loss_fn(score_model, test_x, marginal_prob_std_fn, eps=eps).item()
eval_loss /= len(test_loader)
eval_losses.append(eval_loss)
score_model.train() # Set the model back to training mode
# Sample and visualize
if iteration % sampling_freq == 0 and iteration > 0:
score_model.eval() # Set the model to evaluation mode for sampling
t = 1e-5
vec_t = torch.ones(grid_tensor.shape[0], device=device) * t
scores = score_eval_wrapper(grid_tensor.to(device), vec_t, score_model)
samples = Euler_Maruyama_sampler(score_model,
marginal_prob_std_fn,
diffusion_coeff_fn,
1000,
device=device)
name = "{}_{}_samples_{}.png".format("vesde", dataset_name, iteration)
if sampling_dir is not None:
save_path = os.path.join(sampling_dir, name)
plot_score2DCircle(grid_tensor, samples.detach().cpu(), scores, x.cpu(),
figsize=(6, 6), fontsize=8, save_path=save_path)
score_model.train()
if model_save_dir is not None:
model_save_path = os.path.join(model_save_dir, f'ckpt_{iteration}.pth')
torch.save(score_model.state_dict(), model_save_path)
print(f"Model saved at iteration {iteration} to {model_save_path}")
# Plot final training and evaluation loss curves:
window_size = 100
plt.figure(figsize=(12, 6))
plt.plot(losses[1:], 'b-', alpha=0.3, label='Training Loss')
plt.plot(range(log_freq, total_iterations + 1, log_freq), eval_losses, 'g-', label='Evaluation Loss')
if len(losses[1:]) >= window_size:
moving_avg = np.convolve(losses[1:], np.ones(window_size)/window_size, mode='valid')
plt.plot(range(window_size-1, len(losses)-1), moving_avg, 'r-',
label=f'Moving Average (window={window_size})')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.yscale('log')
plt.grid(True)
plt.legend(loc='upper right')
plt.title('Training and Evaluation Loss Evolution')
plt.savefig(os.path.join(sampling_dir, 'loss_evolution.png'))
plt.show()
return score_model
#------------------------------------------------------------------------------------------------
def train_model(sample_size=2,
n_iter=100,
sampling_freq=1000,
batch_size=500,
sigma=1.0,
eps=1e-5,
):
print("Training model over eps={}".format(eps))
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Prepare datasets
train_subset, test_subset = prepare_datasets(sample_size)
train_loader = DataLoader(train_subset, batch_size=min(batch_size, sample_size), shuffle=True)
test_loader = DataLoader(test_subset, batch_size=min(batch_size, sample_size), shuffle=True)
patterns = next(iter(train_loader))
print(patterns.shape)
# Create results directory based on sample_size
results_dir = f'./results/toy_example_results/sample_size_{sample_size}'
sample_dir = os.path.join(results_dir, "samples")
model_dir = os.path.join(results_dir, "models")
os.makedirs(results_dir, exist_ok=True)
os.makedirs(sample_dir, exist_ok=True)
os.makedirs(model_dir, exist_ok=True)
save_circle_plot(
patterns,
save_dir=results_dir,
filename=f"2dcircle_data_samples",
figsize=(3, 3),
fontsize=6,
show=False
)
# Define SDE and related functions
vesde = VESDETerms(sigma, device)
marginal_prob_std_fn = vesde.marginal_prob_std
diffusion_coeff_fn = vesde.diffusion_coeff
# Define score model
score_model = ScoreNet(marginal_prob_std=marginal_prob_std_fn)
score_model = score_model.to(device)
optimizer = torch.optim.Adam(score_model.parameters(), lr=1e-4)
# Train the score model
score_model = train_score_model(
score_model=score_model,
train_loader=train_loader,
test_loader=test_loader,
optimizer=optimizer,
total_iterations=n_iter,
device=device,
marginal_prob_std_fn=marginal_prob_std_fn,
diffusion_coeff_fn=diffusion_coeff_fn,
eps=eps,
sampling_dir=sample_dir,
model_save_dir=model_dir,
sampling_freq=sampling_freq
)
#------------------------------------------------------------------------------------------------
# Likelihood Computation as described in Song et al. 2021 using the Laplacian instead of the Hutchinson trace estimator
def prior_likelihood(z, sigma):
"""The likelihood of a Gaussian distribution with mean zero and
standard deviation sigma."""
shape = z.shape
N = np.prod(shape[1:])
return -N / 2. * torch.log(2*np.pi*sigma**2) - torch.sum(z**2, dim=1) / (2 * sigma**2)
def compute_laplacian(score_fn, x, t):
"""Compute the Laplacian of the score function."""
laplacian = torch.zeros(x.size(0), device=x.device)
with torch.enable_grad():
x.requires_grad_(True)
score = score_fn(x, t)
for i in range(x.shape[1]): # Iterate over dimensions
grad_score_i = torch.autograd.grad(score[:, i].sum(), x, create_graph=True)[0][:, i]
laplacian += grad_score_i
x.requires_grad_(False) # Make sure to disable gradient tracking after computation
return laplacian.detach() # Detach the tensor to avoid gradient tracking issues
def ode_likelihood_with_laplacian(x,
score_model,
marginal_prob_std,
diffusion_coeff,
batch_size=64,
device='cuda',
eps=1e-5):
"""Compute the likelihood with probability flow ODE using explicit Laplacian."""
shape = x.shape
def score_eval_wrapper(sample, time_steps):
"""A wrapper for evaluating the score-based model for the ODE solver."""
sample = torch.tensor(sample, device=device, dtype=torch.float32).reshape(shape)
time_steps = torch.tensor(time_steps, device=device, dtype=torch.float32).reshape((sample.shape[0], ))
with torch.no_grad():
score = score_model(sample, time_steps)
return score.cpu().numpy().reshape((-1, shape[1])).astype(np.float64)
def laplacian_eval_wrapper(sample, time_steps):
"""A wrapper for evaluating the Laplacian of the score function."""
sample = torch.tensor(sample, device=device, dtype=torch.float32).reshape(shape)
time_steps = torch.tensor(time_steps, device=device, dtype=torch.float32).reshape((sample.shape[0], ))
laplacian = compute_laplacian(score_model, sample, time_steps)
return laplacian.cpu().numpy().reshape((-1,)).astype(np.float64)
def ode_func(t, x):
"""The ODE function for the solver."""
time_steps = np.ones((shape[0],)) * t
sample = x[:-shape[0]]
g = diffusion_coeff(torch.tensor(t)).cpu().numpy()
drift = -0.5 * g**2 * score_eval_wrapper(sample, time_steps)
logp_grad = -0.5 * g**2 * laplacian_eval_wrapper(sample, time_steps)
return np.concatenate([drift.reshape(-1), logp_grad], axis=0)
init = np.concatenate([x.cpu().numpy().reshape((-1,)), np.zeros((shape[0],))], axis=0)
# Black-box ODE solver
res = integrate.solve_ivp(ode_func, (eps, 1.), init, rtol=1e-5, atol=1e-5, method='RK45')
zp = torch.tensor(res.y[:, -1], device=device)
z = zp[:-shape[0]].reshape(shape)
delta_logp = zp[-shape[0]:].reshape(shape[0])
sigma_max = marginal_prob_std(1.)
prior_logp = prior_likelihood(z, sigma_max)
logp = prior_logp + delta_logp
return logp
#------------------------------------------------------------------------------------------------
# Energy
def potential_energy(logp, t=1e-5, std=1):
energy = - logp * (2 * t * std*2 )
return energy
#------------------------------------------------------------------------------------------------
# Utils for energy visualizaiton
def compute_clusters(samples, distance_threshold=1.0):
"""
Compute clusters from samples using hierarchical clustering.
"""
# Convert samples to numpy if needed
samples_np = samples.cpu().numpy() if torch.is_tensor(samples) else samples
# Perform hierarchical clustering
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=distance_threshold
).fit(samples_np)
# Compute cluster centers
unique_labels = np.unique(clustering.labels_)
cluster_centers = np.array([
samples_np[clustering.labels_ == label].mean(axis=0)
for label in unique_labels
])
return cluster_centers, clustering.labels_
def dbscan_clustering(samples, eps=0.5, min_samples=5):
"""
Perform density-based clustering (DBSCAN).
Parameters:
samples (numpy.ndarray or torch.Tensor): Input data points.
eps (float): Maximum distance between points in a cluster.
min_samples (int): Minimum points needed to form a cluster.
Returns:
tuple: (cluster_centers, cluster_labels)
"""
samples_np = samples.cpu().numpy() if torch.is_tensor(samples) else samples
clustering = DBSCAN(eps=eps, min_samples=min_samples).fit(samples_np)
labels = clustering.labels_
unique_labels = np.unique(labels[labels >= 0]) # Ignore noise (-1)
# Compute cluster centers
cluster_centers = np.array([
samples_np[labels == label].mean(axis=0)
for label in unique_labels
])
return cluster_centers, labels
def kmeans_clustering(samples, n_clusters=2):
"""
Perform K-Means clustering.
Parameters:
samples (numpy.ndarray or torch.Tensor): Input data points.
n_clusters (int): Number of clusters.
Returns:
tuple: (cluster_centers, cluster_labels)
"""
samples_np = samples.cpu().numpy() if torch.is_tensor(samples) else samples
clustering = KMeans(n_clusters=n_clusters, random_state=42).fit(samples_np)
return clustering.cluster_centers_, clustering.labels_
def get_optimal_distance_threshold(distances, samples, sample_size, save_dir=None):
"""
Dynamically finds the optimal distance threshold by identifying the valley (local minimum)
between peaks in the pairwise distance distribution.
Parameters:
distances (numpy.ndarray): A 1D array of pairwise distances.
plot (bool): If True, visualizes the distance distribution and threshold.
Returns:
float: The optimal distance threshold for clustering.
"""
# Compute pairwise distances
flat_distances = distances[np.triu_indices(len(samples), k=1)]
# Estimate density to find peaks and valleys
density = gaussian_kde(flat_distances)
x_vals = np.linspace(flat_distances.min(), flat_distances.max(), 500)
density_vals = density(x_vals)
# Find peaks (clusters) and valleys (potential thresholds)
peaks, _ = find_peaks(density_vals)
valleys, _ = find_peaks(-density_vals) # Negative peaks = valleys
# Count peaks that have at least 1 or more elements
num_valid_peaks = sum(density_vals[peaks] > 0) + sum(density_vals[valleys] > 0)
print("Number of valid peaks: ", num_valid_peaks)
# Choose the first valley between the two highest peaks as the threshold
if len(valleys) > 0:
distance_threshold = x_vals[valleys[0]] # First valley
else:
distance_threshold = np.median(flat_distances) # Fallback
# Optional: Plot the histogram with the detected threshold
if save_dir is not None:
plt.figure(figsize=(8, 5))
plt.hist(flat_distances, bins=50, alpha=0.5, density=True, label="Pairwise Distances")
plt.plot(x_vals, density_vals, label="Density Estimate", color='blue')
# Mark peaks and valleys
plt.scatter(x_vals[peaks], density_vals[peaks], color='red', label="Peaks", zorder=3)
plt.scatter(x_vals[valleys], density_vals[valleys], color='green', label="Valleys", zorder=3)
plt.axvline(distance_threshold, color='black', linestyle='--', label=f"Threshold: {distance_threshold:.2f}")
plt.xlabel("Pairwise Distance")
plt.ylabel("Density")
plt.legend()
plt.savefig(os.path.join(save_dir, 'distance_threshold_sample_size_{}.png'.format(sample_size)))
return distance_threshold, num_valid_peaks
#------------------------------------------------------------------------------------------------
# Evaluate the model
def load_model(model_dir, checkpoint, sigma=1.0):
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Define SDE terms
vesde = VESDETerms(sigma, device)
marginal_prob_std_fn = vesde.marginal_prob_std
diffusion_coeff_fn = vesde.diffusion_coeff
# Initialize the model
score_model = ScoreNet(marginal_prob_std=marginal_prob_std_fn)
score_model = score_model.to(device)
# Load the model state_dict
model_path = os.path.join(model_dir, f"ckpt_{checkpoint}.pth")
if not os.path.exists(model_path):
raise FileNotFoundError(f"Model file not found at {model_path}")
score_model.load_state_dict(torch.load(model_path, map_location=device))
score_model.eval()
return score_model, marginal_prob_std_fn, diffusion_coeff_fn
def evaluate_model(sample_size=2, t=0.15, checkpoint=500000, batch_size=10000, distance_threshold=1.0, dynamic_threshold=False):
device = 'cuda' if torch.cuda.is_available() else 'cpu'
workdir = f'./results/toy_example_results/sample_size_{sample_size}'
model_dir = os.path.join(workdir, "models")
sample_dir = os.path.join(workdir, "energy_plots")
os.makedirs(sample_dir, exist_ok=True)
# Load Data
train_subset, _ = prepare_datasets(sample_size)
train_loader = DataLoader(train_subset, batch_size=sample_size, shuffle=True)
patterns = next(iter(train_loader))
# Load Model
score_model, marginal_prob_std_fn, diffusion_coeff_fn = load_model(model_dir, checkpoint)
# Sample from the model
samples = Euler_Maruyama_sampler(score_model,
marginal_prob_std_fn,
diffusion_coeff_fn,
batch_size,
device=device)
if dynamic_threshold:
print("Finding the optimal threshold dynamically")
# Compute pairwise distances
distances = distance_matrix(samples.cpu().numpy(), samples.cpu().numpy())
# Find the optimal threshold
distance_threshold, num_valid_peaks = get_optimal_distance_threshold(distances, samples, sample_size, save_dir=sample_dir)
cluster_centers, cluster_labels = dbscan_clustering(samples, eps=distance_threshold, min_samples=2)
else:
distance_threshold = distance_threshold
print("Using the provided distance threshold: ", distance_threshold)
cluster_centers, cluster_labels = compute_clusters(samples, distance_threshold=distance_threshold)
# cluster_centers, cluster_labels = kmeans_clustering(samples, n_clusters=num_valid_peaks)
# ------------------------------------------------------------------------------------------------
print("Model evaluation with distance threshold: ", distance_threshold)
# Create a grid of points for evaluation
grid_tensor = create_grid(resolution=20)[2].clone().detach().to(torch.float32)
# Gets the likelihood at t_0 with ode_likelihood_with_laplacian
logp = ode_likelihood_with_laplacian(grid_tensor.to(device),
score_model,
marginal_prob_std_fn,
diffusion_coeff_fn,
grid_tensor.shape[0],
device=device,
eps=t)
# Compute the energy at a given time
vec_t = torch.ones(grid_tensor.shape[0], device=device) * t
energy = potential_energy(logp, t=t)
normalized_energy = energy - energy.min()
scores = score_eval_wrapper(grid_tensor.to(device), vec_t, score_model)
lopg_clusters = ode_likelihood_with_laplacian(torch.tensor(cluster_centers, device=device),
score_model,
marginal_prob_std_fn,
diffusion_coeff_fn,
device=device,
eps=t)
cluster_energies = potential_energy(lopg_clusters, t)
cluster_energies = cluster_energies - cluster_energies.min()
# cluster_energies = torch.round(potential_energy(lopg_clusters, t_energy) * 100) / 100
cluster_data = (cluster_centers, cluster_labels, cluster_energies)
plot_energy_landscape(normalized_energy,
scores,
grid_tensor,
samples,
patterns,
sample_size,
cluster_data=cluster_data,
save_dir=sample_dir,
fontsize=14,
reversed=False,
legend=False)
#------------------------------------------------------------------------------------------------
# Compute the Basin of attraction
def inject_noise(x0, t, marginal_prob_std_fn, device="cpu"):
# Get a noisy version of the patterns for a given time step
t_vec = torch.full((x0.shape[0],), t, device=device)
z = torch.randn_like(x0, device=device)
std = marginal_prob_std_fn(t_vec).to(device)
perturbed_x = x0 + z * std[:, None]
return perturbed_x
def Euler_Maruyama_sampler(score_model,
marginal_prob_std,
diffusion_coeff,
batch_size=64,
num_steps=1000,
device='cuda',
eps=1e-3):
"""Generate samples from score-based models with the Euler-Maruyama solver."""
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 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] * score_model(x, batch_time_step) * step_size
x = mean_x + torch.sqrt(step_size) * g[:, None] * torch.randn_like(x)
# Do not include any noise in the last sampling step.
return mean_x
@torch.no_grad()
def reverse_diffusion_sample(score_model, x_t, t, diffusion_coeff_fn, device='cpu', eps=1e-3):
batch_size = x_t.size(0)
num_steps = int(1000 * t)
time_steps = torch.linspace(t, eps, num_steps, device=device, dtype=torch.float32) # Set dtype to float32
step_size = time_steps[0] - time_steps[1]
x = x_t.clone().to(device, dtype=torch.float32) # Ensure dtype consistency
for time_step in tqdm(time_steps, desc="Reverse diffusion"):
batch_time_step = torch.ones(batch_size, device=device, dtype=torch.float32) * time_step
g = diffusion_coeff_fn(batch_time_step).to(dtype=torch.float32) # Convert to float32
drift = (g**2)[:, None] * score_model(x, batch_time_step) * step_size
x_mean = x + drift
x = x_mean + torch.sqrt(step_size) * g[:, None] * torch.randn_like(x, dtype=torch.float32)
return x_mean
def euclidean_distance(x, y):
""" Returns ||x - y||_2 per sample. x, y shape: (B,2). """
return torch.norm(x - y, dim=-1)
# Simulation: Inject noise at time t and reverse back
def simulate_noise_injection_and_reversal(patterns, score_model, diffusion_coeff_fn, marginal_prob_std_fn, t=0.5, device='cpu'):
patterns = patterns.to(device)
noisy_patterns = inject_noise(patterns, t, marginal_prob_std_fn, device=device)
reversed_patterns = reverse_diffusion_sample(score_model.to(device), noisy_patterns, t,
diffusion_coeff_fn, device=device)
return patterns, noisy_patterns, reversed_patterns
# Plot the original, noisy, and reversed patterns