-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvis.py
More file actions
1744 lines (1430 loc) · 69.1 KB
/
vis.py
File metadata and controls
1744 lines (1430 loc) · 69.1 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
#!/usr/bin/env python3
"""
Comprehensive Visualization System for Diffusion Models
=======================================================
This module provides a unified visualization system for DDPM, SM, and NCSM models.
Includes training visualizations, sampling animations, and score comparisons.
"""
import os
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
from typing import Dict, List, Any, Optional, Tuple
import warnings
warnings.filterwarnings('ignore')
# Set matplotlib backend
plt.switch_backend('Agg')
def _get_noise_levels_from_config(config: Dict[str, Any]) -> List[float]:
"""
Helper function to generate noise levels from config parameters.
Uses the same logic as training to ensure consistency.
"""
from models.ncsm import create_noise_schedule
return create_noise_schedule(
sigma_min=config['sigma_min'],
sigma_max=config['sigma_max'],
num_scales=config['num_noise_scales']
)
# Global plot parameters for consistent styling
PLOT_BOUNDS = (-0.5, 0.5, -0.5, 0.5) # Match actual dataset bounds
POINT_SIZE = 20 # Bigger, more visible points
FIGURE_SIZE = (6, 6) # Smaller figures make text and points appear bigger
DPI = 150
# Unified color scheme
COLORS = {
'training': 'blue', # Training data always blue
'ddpm': 'red', # DDPM model red
'sm': 'green', # Score Matching model green
'ncsm': 'orange', # NCSM model orange
'loss_raw': 'blue', # Raw loss curve
'loss_smooth': 'red', # Smoothed loss curve
'contour': 'lightgray', # PDF contour lines
}
# Unified font sizes
FONT_SIZES = {
'title': 16, # Plot titles
'axis_label': 14, # X/Y axis labels
'legend': 12, # Legend text
'annotation': 12, # Animation annotations
'tick_label': 12, # Axis tick labels
}
def plot_losses(losses: List[float], model_type: str, config: Dict[str, Any], show: bool = True):
"""
Plot training losses over time.
Args:
losses: List of loss values
model_type: Type of model ('ddpm', 'sm', 'ncsm')
config: Configuration dictionary
show: Whether to show the plot
"""
plt.figure(figsize=(FIGURE_SIZE[0]*2, FIGURE_SIZE[1]))
# Convert to numpy array for easier manipulation
losses_array = np.array(losses)
# Plot raw losses
plt.plot(losses_array, alpha=0.6, color=COLORS['loss_raw'], linewidth=1)
# Add smoothed version if we have enough data points
if len(losses) > 50:
window_size = min(50, len(losses) // 10)
smoothed = np.convolve(losses_array, np.ones(window_size)/window_size, mode='valid')
plt.plot(range(window_size-1, len(losses)), smoothed,
color=COLORS['loss_smooth'], linewidth=2, label='Smoothed')
plt.legend(fontsize=FONT_SIZES['legend'])
plt.title(f'{model_type.upper()} Training Loss', fontsize=FONT_SIZES['title'])
plt.xlabel('Epoch' if model_type == 'ddpm' else 'Step', fontsize=FONT_SIZES['axis_label'])
plt.ylabel('Loss', fontsize=FONT_SIZES['axis_label'])
plt.grid(True, alpha=0.3)
plt.tick_params(axis='both', which='major', labelsize=FONT_SIZES['tick_label'])
# Save to figures directory
os.makedirs('./figures', exist_ok=True)
save_path = os.path.join('./figures', f'{model_type}_losses.png')
plt.savefig(save_path, dpi=DPI, bbox_inches='tight')
print(f"Saved loss plot: {save_path}")
if show:
plt.show()
else:
plt.close()
def plot_samples(samples: torch.Tensor,
title: str = "Generated Samples",
save_path: Optional[str] = None,
show_plot: bool = True,
figsize: Tuple[int, int] = (5, 5)) -> None:
"""
Plot generated samples.
Args:
samples: Generated samples to plot
title: Title for the plot
save_path: Path to save the plot
show_plot: Whether to show the plot
figsize: Figure size
"""
fig, ax = plt.subplots(figsize=figsize)
# Convert to numpy for plotting
if isinstance(samples, torch.Tensor):
samples_np = samples.detach().cpu().numpy()
else:
samples_np = samples
# Plot samples
ax.scatter(samples_np[:, 0], samples_np[:, 1],
s=POINT_SIZE, alpha=0.7, color='blue', label='Generated')
# Set bounds and styling
ax.set_xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
ax.set_ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
ax.set_xlabel('X', fontsize=FONT_SIZES['axis_label'])
ax.set_ylabel('Y', fontsize=FONT_SIZES['axis_label'])
ax.set_title(title, fontsize=FONT_SIZES['title'])
ax.grid(True, alpha=0.3)
ax.legend(fontsize=FONT_SIZES['legend'], loc='upper right')
# Make tick labels larger
ax.tick_params(axis='both', which='major', labelsize=FONT_SIZES['tick_label'])
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
if show_plot:
plt.show()
else:
plt.close()
def plot_data_comparison(training_data: torch.Tensor,
generated_data: torch.Tensor,
model_type: str,
save_path: Optional[str] = None,
show_plot: bool = True,
dataset=None,
figsize: Tuple[int, int] = (10, 5)) -> None:
"""
Plot comparison between training data and generated samples with true PDF contours.
Args:
training_data: Training data samples (with fixed seed)
generated_data: Generated samples from model
model_type: Type of model ('ddpm', 'sm', 'ncsm')
save_path: Path to save the plot
show_plot: Whether to show the plot
dataset: Dataset instance (for PDF contours)
figsize: Figure size (smaller for larger fonts)
"""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
# Convert to numpy for plotting
if isinstance(training_data, torch.Tensor):
training_np = training_data.detach().cpu().numpy()
else:
training_np = training_data
if isinstance(generated_data, torch.Tensor):
generated_np = generated_data.detach().cpu().numpy()
else:
generated_np = generated_data
# Create PDF contour background if dataset is provided
if dataset is not None:
x_min, x_max, y_min, y_max = PLOT_BOUNDS
x_grid = np.linspace(x_min, x_max, 100)
y_grid = np.linspace(y_min, y_max, 100)
X, Y = np.meshgrid(x_grid, y_grid)
points = np.stack([X.ravel(), Y.ravel()], axis=1)
# Compute PDF values
pdf_values = dataset.pdf(X.ravel(), Y.ravel())
pdf_grid = pdf_values.reshape(X.shape)
# Add contour lines to both plots
levels = np.linspace(0.1, pdf_values.max(), 8)
ax1.contour(X, Y, pdf_grid, levels=levels, colors='lightgray', alpha=0.6, linewidths=0.8)
ax2.contour(X, Y, pdf_grid, levels=levels, colors='lightgray', alpha=0.6, linewidths=0.8)
# Plot training data
ax1.scatter(training_np[:, 0], training_np[:, 1],
s=POINT_SIZE, alpha=0.7, color=COLORS['training'], label='Training')
ax1.set_xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
ax1.set_ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
ax1.set_xlabel('X', fontsize=FONT_SIZES['axis_label'])
ax1.set_ylabel('Y', fontsize=FONT_SIZES['axis_label'])
ax1.set_title('Training Data', fontsize=FONT_SIZES['title'])
ax1.grid(True, alpha=0.3)
ax1.legend(fontsize=FONT_SIZES['legend'], loc='upper right')
ax1.tick_params(axis='both', which='major', labelsize=FONT_SIZES['tick_label'])
# Plot generated samples with model-specific color
model_color = COLORS.get(model_type, 'blue') # Default to blue if model not found
ax2.scatter(generated_np[:, 0], generated_np[:, 1],
s=POINT_SIZE, alpha=0.7, color=model_color, label='Generated')
ax2.set_xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
ax2.set_ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
ax2.set_xlabel('X', fontsize=FONT_SIZES['axis_label'])
ax2.set_ylabel('Y', fontsize=FONT_SIZES['axis_label'])
ax2.set_title(f'{model_type.upper()} Generated', fontsize=FONT_SIZES['title'])
ax2.grid(True, alpha=0.3)
ax2.legend(fontsize=FONT_SIZES['legend'], loc='upper right')
ax2.tick_params(axis='both', which='major', labelsize=FONT_SIZES['tick_label'])
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
if show_plot:
plt.show()
else:
plt.close()
def save_samples_grid(samples: torch.Tensor,
model_type: str,
config: Dict[str, Any],
save_name: Optional[str] = None,
figsize: Tuple[int, int] = (8, 8)) -> str:
"""
Save a grid of generated samples.
Args:
samples: Generated samples
model_type: Type of model ('ddpm', 'sm', 'ncsm')
config: Configuration dictionary
save_name: Optional custom save name
figsize: Figure size
Returns:
Path to saved figure
"""
plt.figure(figsize=figsize)
# Convert to numpy
if isinstance(samples, torch.Tensor):
samples_np = samples.detach().cpu().numpy()
else:
samples_np = samples
# Create scatter plot with uniform styling
model_color = COLORS.get(model_type, 'blue') # Default to blue if model not found
plt.scatter(samples_np[:, 0], samples_np[:, 1],
s=POINT_SIZE, alpha=0.6, c=model_color, edgecolors='none')
plt.xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
plt.ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
plt.gca().set_aspect('equal')
plt.grid(True, alpha=0.3)
plt.title(f'{model_type.upper()} Generated Samples', fontsize=FONT_SIZES['title'])
plt.xlabel('X', fontsize=FONT_SIZES['axis_label'])
plt.ylabel('Y', fontsize=FONT_SIZES['axis_label'])
plt.tick_params(axis='both', which='major', labelsize=FONT_SIZES['tick_label'])
# Save to figures directory
os.makedirs('./figures', exist_ok=True)
if save_name is None:
save_name = f'{model_type}_samples.png'
save_path = os.path.join('./figures', save_name)
plt.savefig(save_path, dpi=DPI, bbox_inches='tight')
print(f"Saved samples: {save_path}")
plt.close()
return save_path
def plot_dataset_overview(dataset, n_samples: int = 2000, n_grid: int = 200,
save_path: Optional[str] = None, show: bool = True,
figsize: Tuple[int, int] = (12, 5)) -> str:
"""
Create a double plot showing training data samples and PDF contours.
Args:
dataset: SmilingFaceDataset instance
n_samples: Number of samples to generate and plot
n_grid: Grid resolution for PDF contour plot
save_path: Optional path to save the plot
show: Whether to display the plot
figsize: Figure size tuple
Returns:
Path where the plot was saved
"""
# Generate samples
samples = dataset.sample(n_samples, return_tensor=False)
# Create evaluation grid for PDF
x_min, x_max, y_min, y_max = dataset.get_bounds()
xs = np.linspace(x_min, x_max, n_grid)
ys = np.linspace(y_min, y_max, n_grid)
X, Y = np.meshgrid(xs, ys)
# Evaluate PDF
PDF_vals = dataset.pdf(X, Y)
# Create figure with subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
fig.suptitle('Smiling Face Dataset Overview', fontsize=16, fontweight='bold')
# Left plot: Training data samples
ax1.scatter(samples[:, 0], samples[:, 1], alpha=0.6, s=POINT_SIZE, c='blue')
ax1.set_xlim(x_min, x_max)
ax1.set_ylim(y_min, y_max)
ax1.set_xlabel('X coordinate')
ax1.set_ylabel('Y coordinate')
ax1.set_title(f'Training Data Samples (n={n_samples})')
ax1.grid(True, alpha=0.3)
ax1.set_aspect('equal', adjustable='box')
# Right plot: PDF contours
contour = ax2.contourf(X, Y, PDF_vals, levels=50, cmap='viridis')
ax2.set_xlim(x_min, x_max)
ax2.set_ylim(y_min, y_max)
ax2.set_xlabel('X coordinate')
ax2.set_ylabel('Y coordinate')
ax2.set_title('Probability Density Function')
ax2.grid(True, alpha=0.3)
ax2.set_aspect('equal', adjustable='box')
# Add colorbar for PDF
cbar = plt.colorbar(contour, ax=ax2)
cbar.set_label('PDF Value')
plt.tight_layout()
# Save the plot
if save_path is None:
os.makedirs("figures", exist_ok=True)
save_path = "figures/dataset_overview.png"
plt.savefig(save_path, dpi=DPI, bbox_inches='tight', facecolor='white')
print(f"📊 Dataset overview saved to: {save_path}")
if show:
plt.show()
else:
plt.close()
return save_path
def plot_score_comparison(model,
model_type: str,
training_data: torch.Tensor,
generated_data: torch.Tensor,
save_path: Optional[str] = None,
show_plot: bool = True,
noise_levels: Optional[List[float]] = None,
n_grid: int = 15,
dataset=None) -> None:
"""
Plot comparison between predicted and true score fields side by side.
Args:
model: Trained model
model_type: Type of model ('sm', 'ncsm')
training_data: Training data samples
generated_data: Generated data samples
save_path: Path to save the plot
show_plot: Whether to show the plot
noise_levels: Noise levels for NCSM (optional)
n_grid: Grid size for score visualization
dataset: Dataset object (for true score function)
"""
# Create side-by-side plots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(FIGURE_SIZE[0]*2, FIGURE_SIZE[1]))
# Create grid for score evaluation
x = np.linspace(PLOT_BOUNDS[0], PLOT_BOUNDS[1], n_grid)
y = np.linspace(PLOT_BOUNDS[2], PLOT_BOUNDS[3], n_grid)
X, Y = np.meshgrid(x, y)
# Prepare grid points
grid_points = np.column_stack([X.ravel(), Y.ravel()])
grid_tensor = torch.FloatTensor(grid_points).to(next(model.parameters()).device)
# Add PDF contour lines if dataset is available
if dataset is not None:
# Create finer grid for PDF contours
x_pdf = np.linspace(PLOT_BOUNDS[0], PLOT_BOUNDS[1], 100)
y_pdf = np.linspace(PLOT_BOUNDS[2], PLOT_BOUNDS[3], 100)
X_pdf, Y_pdf = np.meshgrid(x_pdf, y_pdf)
# Compute PDF values
pdf_values = dataset.pdf(X_pdf.ravel(), Y_pdf.ravel())
pdf_grid = pdf_values.reshape(X_pdf.shape)
# Add contour lines to both plots
levels = np.linspace(0.1, pdf_values.max(), 8)
ax1.contour(X_pdf, Y_pdf, pdf_grid, levels=levels, colors=COLORS['contour'],
alpha=0.6, linewidths=0.8)
ax2.contour(X_pdf, Y_pdf, pdf_grid, levels=levels, colors=COLORS['contour'],
alpha=0.6, linewidths=0.8)
# Get true scores (if dataset available)
if dataset is not None:
true_scores = dataset.true_score(grid_tensor[:, 0], grid_tensor[:, 1])
if isinstance(true_scores, torch.Tensor):
true_scores = true_scores.detach().cpu().numpy()
# Plot true score field
U_true = true_scores[:, 0].reshape(n_grid, n_grid)
V_true = true_scores[:, 1].reshape(n_grid, n_grid)
# Calculate magnitude and scale separately for visibility
M_true = np.sqrt(U_true**2 + V_true**2)
M_true_max = np.max(M_true)
if M_true_max > 0:
scale_factor = 1.0 / M_true_max
U_true_scaled = U_true * scale_factor
V_true_scaled = V_true * scale_factor
else:
U_true_scaled = U_true
V_true_scaled = V_true
ax1.quiver(X, Y, U_true_scaled, V_true_scaled,
scale=10.0, scale_units='xy', angles='xy', alpha=0.7, color=COLORS['training'])
ax1.set_title('True Score Field', fontsize=FONT_SIZES['title'])
else:
ax1.text(0.5, 0.5, 'Dataset not available\nfor true score',
transform=ax1.transAxes, ha='center', va='center', fontsize=FONT_SIZES['annotation'])
ax1.set_title('True Score Field (N/A)', fontsize=FONT_SIZES['title'])
# Get predicted scores
model.eval()
with torch.no_grad():
if model_type == 'sm':
predicted_scores = model(grid_tensor).detach().cpu().numpy()
elif model_type == 'ncsm':
# Use the first noise level for NCSM
noise_level = noise_levels[0] if noise_levels else 0.1
noise_tensor = torch.full((grid_tensor.shape[0], 1), noise_level,
device=grid_tensor.device, dtype=grid_tensor.dtype)
predicted_scores = model(grid_tensor, noise_tensor).detach().cpu().numpy()
else:
predicted_scores = np.zeros_like(grid_points)
# Plot predicted score field
U_pred = predicted_scores[:, 0].reshape(n_grid, n_grid)
V_pred = predicted_scores[:, 1].reshape(n_grid, n_grid)
# Calculate magnitude and scale separately for visibility
M_pred = np.sqrt(U_pred**2 + V_pred**2)
M_pred_max = np.max(M_pred)
if M_pred_max > 0:
scale_factor = 1.0 / M_pred_max
U_pred_scaled = U_pred * scale_factor
V_pred_scaled = V_pred * scale_factor
else:
U_pred_scaled = U_pred
V_pred_scaled = V_pred
# Use model-specific color for predicted scores
model_color = COLORS.get(model_type, 'blue')
ax2.quiver(X, Y, U_pred_scaled, V_pred_scaled,
scale=10.0, scale_units='xy', angles='xy', alpha=0.7, color=model_color)
title = f'Predicted Score Field ({model_type.upper()})'
if model_type == 'ncsm' and noise_levels:
title += f' (σ={noise_levels[0]:.3f})'
ax2.set_title(title, fontsize=FONT_SIZES['title'])
# Set bounds and styling for both plots
for ax in [ax1, ax2]:
ax.set_xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
ax.set_ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
ax.set_xlabel('X', fontsize=FONT_SIZES['axis_label'])
ax.set_ylabel('Y', fontsize=FONT_SIZES['axis_label'])
ax.grid(True, alpha=0.3)
ax.tick_params(axis='both', which='major', labelsize=FONT_SIZES['tick_label'])
ax.set_aspect('equal')
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Saved score comparison: {save_path}")
if show_plot:
plt.show()
else:
plt.close()
def plot_score_distance(model_type: str,
model,
dataset,
config: Dict[str, Any],
device: torch.device,
n_grid: int = 50,
noise_level: float = 0.1,
save_name: Optional[str] = None,
show: bool = True) -> str:
"""
Plot distance between predicted and true scores.
Args:
model_type: Type of model ('sm', 'ncsm')
model: Trained model
dataset: Dataset
config: Configuration dictionary
device: Device to run on
n_grid: Grid resolution
noise_level: Noise level (for NCSM)
save_name: Optional custom save name
show: Whether to show the plot
Returns:
Path to saved figure
"""
# Create grid
x = np.linspace(PLOT_BOUNDS[0], PLOT_BOUNDS[1], n_grid)
y = np.linspace(PLOT_BOUNDS[2], PLOT_BOUNDS[3], n_grid)
X, Y = np.meshgrid(x, y)
# Prepare grid points
grid_points = np.column_stack([X.ravel(), Y.ravel()])
grid_tensor = torch.FloatTensor(grid_points).to(device)
# Get true scores
true_scores = dataset.true_score(grid_tensor[:, 0], grid_tensor[:, 1])
if isinstance(true_scores, torch.Tensor):
true_scores = true_scores.detach().cpu().numpy()
# Get predicted scores
model.eval()
with torch.no_grad():
if model_type == 'sm':
predicted_scores = model(grid_tensor).detach().cpu().numpy()
elif model_type == 'ncsm':
# Add noise level as separate input
noise_tensor = torch.full((grid_tensor.shape[0], 1), noise_level,
device=device, dtype=grid_tensor.dtype)
predicted_scores = model(grid_tensor, noise_tensor).detach().cpu().numpy()
# Compute distances
distances = np.linalg.norm(predicted_scores - true_scores, axis=1)
distances = distances.reshape(n_grid, n_grid)
# Create heatmap
plt.figure(figsize=FIGURE_SIZE)
plt.imshow(distances, extent=[PLOT_BOUNDS[0], PLOT_BOUNDS[1], PLOT_BOUNDS[2], PLOT_BOUNDS[3]],
origin='lower', cmap='viridis', aspect='equal')
plt.colorbar(label='L2 Distance')
title = f'{model_type.upper()} Score Distance'
if model_type == 'ncsm':
title += f' (σ={noise_level:.3f})'
plt.title(title)
plt.xlabel('x')
plt.ylabel('y')
# Save to figures directory
os.makedirs('./figures', exist_ok=True)
if save_name is None:
if model_type == 'ncsm':
save_name = f'ncsm_score_distance_sigma_{noise_level:.3f}.png'
else:
save_name = f'{model_type}_score_distance.png'
save_path = os.path.join('./figures', save_name)
plt.savefig(save_path, dpi=DPI, bbox_inches='tight')
print(f"Saved score distance: {save_path}")
if show:
plt.show()
else:
plt.close()
return save_path
def plot_noise_schedules(config: Dict[str, Any],
save_path: Optional[str] = None,
show: bool = True,
figsize: Tuple[int, int] = (8, 6)) -> str:
"""
Plot linear and cosine noise schedules for DDPM.
Args:
config: Configuration dictionary containing DDPM parameters
save_path: Optional path to save the plot
show: Whether to display the plot
figsize: Figure size tuple
Returns:
Path where the plot was saved
"""
from models.ddpm import NoiseScheduler
# Get parameters from config or use defaults
num_timesteps = config.get('num_timesteps', 1000)
beta_start = config.get('beta_start', 0.0001)
beta_end = config.get('beta_end', 0.02)
# Create both schedulers
linear_scheduler = NoiseScheduler(
num_timesteps=num_timesteps,
beta_start=beta_start,
beta_end=beta_end,
schedule='linear'
)
cosine_scheduler = NoiseScheduler(
num_timesteps=num_timesteps,
beta_start=beta_start,
beta_end=beta_end,
schedule='cosine'
)
# Create timesteps array
timesteps = torch.arange(num_timesteps)
# Create figure with single plot
fig, ax = plt.subplots(1, 1, figsize=figsize)
fig.suptitle('DDPM Noise Schedules Comparison', fontsize=16, fontweight='bold')
# Plot cumulative alpha values
ax.plot(timesteps.numpy(), linear_scheduler.alphas_cumprod.numpy(),
label='Linear', color='blue', linewidth=2)
ax.plot(timesteps.numpy(), cosine_scheduler.alphas_cumprod.numpy(),
label='Cosine', color='red', linewidth=2)
ax.set_xlabel('Timestep')
ax.set_ylabel('ᾱ(t) = ∏α(s)')
ax.set_title('Cumulative Alpha Schedule')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
# Save the plot
if save_path is None:
os.makedirs("figures", exist_ok=True)
save_path = f"figures/noise_schedules_comparison.png"
plt.savefig(save_path, dpi=DPI, bbox_inches='tight', facecolor='white')
print(f"📊 Noise schedules comparison saved to: {save_path}")
if show:
plt.show()
else:
plt.close()
return save_path
def create_ddpm_sampling_animation(model,
num_samples: int,
config: Dict[str, Any],
device: torch.device,
save_name: Optional[str] = None,
interval: int = 100,
subsample_steps: int = 10,
final_pause_frames: int = 20) -> str:
"""
Create GIF animation of DDPM sampling process.
Args:
model: Trained DDPM model
num_samples: Number of samples to generate
config: Configuration dictionary
device: Device to run on
save_name: Optional custom save name
interval: Animation frame interval in ms
subsample_steps: How many steps to skip between frames
final_pause_frames: Number of extra frames to show final result
Returns:
Path to saved animation
"""
from sampling import DDPMSampler
# Create sampler
sampler = DDPMSampler(model, device)
# Generate samples with trajectory tracking
samples, info = sampler.sample(num_samples, store_trajectory=True,
store_every=subsample_steps, verbose=False)
trajectory = info['trajectory']
timesteps = info['timesteps']
# Create animation
fig, ax = plt.subplots(figsize=FIGURE_SIZE)
ax.set_xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
ax.set_ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
ax.set_title('DDPM Sampling Process', fontsize=FONT_SIZES['title'])
# Initialize scatter plot with bigger points
scat = ax.scatter([], [], s=POINT_SIZE, alpha=0.6, c=COLORS['ddpm'], edgecolors='none')
# Add timestep text
time_text = ax.text(0.02, 0.98, '', transform=ax.transAxes,
fontsize=FONT_SIZES['annotation'], verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
def animate(frame):
# Show normal trajectory frames
if frame < len(trajectory):
data = trajectory[frame].detach().cpu().numpy()
scat.set_offsets(data)
# Update timestep text
if frame < len(timesteps):
t = timesteps[frame]
time_text.set_text(f'Timestep: {t}')
else:
# Show final frame for pause frames
data = trajectory[-1].detach().cpu().numpy()
scat.set_offsets(data)
time_text.set_text('Final Result')
return [scat, time_text]
# Create animation with extended frames (original + pause frames)
total_frames = len(trajectory) + final_pause_frames
anim = FuncAnimation(fig, animate, frames=total_frames,
interval=interval, blit=True, repeat=True)
# Save animation to figures directory
os.makedirs('./figures', exist_ok=True)
if save_name is None:
save_name = f'ddpm_sampling_animation.gif'
save_path = os.path.join('./figures', save_name)
# Save with PillowWriter
writer = PillowWriter(fps=10)
anim.save(save_path, writer=writer)
plt.close()
print(f"Saved DDPM sampling animation: {save_path}")
return save_path
def create_langevin_sampling_animation(score_network,
dataset,
config: Dict[str, Any],
device: torch.device,
num_samples: int = 100,
num_steps: int = None,
step_size: float = None,
save_name: Optional[str] = None,
interval: int = 50,
subsample_steps: int = 10,
final_pause_frames: int = 20) -> str:
"""
Create GIF animation of Langevin sampling process for Score Matching.
Args:
score_network: Trained score network
dataset: Dataset
config: Configuration dictionary
device: Device to run on
num_samples: Number of samples to generate
num_steps: Number of Langevin steps
step_size: Langevin step size
save_name: Optional custom save name
interval: Animation frame interval in ms
subsample_steps: How many steps to skip between frames
final_pause_frames: Number of extra frames to show final result
Returns:
Path to saved animation
"""
from sampling import create_learned_sampler
# Use config values if not provided
if num_steps is None:
num_steps = config['langevin_num_steps']
if step_size is None:
step_size = config['langevin_step_size']
# Create sampler
bounds = dataset.get_bounds()
sampler = create_learned_sampler(score_network, bounds, device, dataset)
# Generate samples with trajectory tracking
samples, info = sampler.sample(num_samples, num_steps, step_size,
store_trajectory=True, store_every=subsample_steps,
verbose=False)
trajectory = info['trajectory']
# Create animation
fig, ax = plt.subplots(figsize=FIGURE_SIZE)
ax.set_xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
ax.set_ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
ax.set_title('Score Matching Langevin Sampling', fontsize=FONT_SIZES['title'])
# Initialize scatter plot with bigger points
scat = ax.scatter([], [], s=POINT_SIZE, alpha=0.6, c=COLORS['sm'], edgecolors='none')
# Add step text
step_text = ax.text(0.02, 0.98, '', transform=ax.transAxes,
fontsize=FONT_SIZES['annotation'], verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
def animate(frame):
# Show normal trajectory frames
if frame < len(trajectory):
data = trajectory[frame].detach().cpu().numpy()
scat.set_offsets(data)
# Update step text
step = frame * subsample_steps
step_text.set_text(f'Step: {step}')
else:
# Show final frame for pause frames
data = trajectory[-1].detach().cpu().numpy()
scat.set_offsets(data)
step_text.set_text('Final Result')
return [scat, step_text]
# Create animation with extended frames (original + pause frames)
total_frames = len(trajectory) + final_pause_frames
anim = FuncAnimation(fig, animate, frames=total_frames,
interval=interval, blit=True, repeat=True)
# Save animation to figures directory
os.makedirs('./figures', exist_ok=True)
if save_name is None:
save_name = f'sm_sampling_animation.gif'
save_path = os.path.join('./figures', save_name)
# Save with PillowWriter
writer = PillowWriter(fps=20)
anim.save(save_path, writer=writer)
plt.close()
print(f"Saved SM sampling animation: {save_path}")
return save_path
def create_annealed_langevin_animation(score_network,
noise_levels: List[float],
dataset,
config: Dict[str, Any],
device: torch.device,
num_samples: int = 100,
steps_per_noise: int = None,
base_step_size: float = None,
save_name: Optional[str] = None,
interval: int = 50,
subsample_steps: int = 5,
final_pause_frames: int = 20) -> str:
"""
Create GIF animation of annealed Langevin sampling process for NCSM.
Args:
score_network: Trained score network
noise_levels: List of noise levels (high to low)
dataset: Dataset
config: Configuration dictionary
device: Device to run on
num_samples: Number of samples to generate
steps_per_noise: Number of steps per noise level
save_name: Optional custom save name
interval: Animation frame interval in ms
subsample_steps: How many steps to skip between frames
final_pause_frames: Number of extra frames to show final result
Returns:
Path to saved animation
"""
from sampling import create_annealed_sampler_from_ncsn
# Use config values if not provided
if steps_per_noise is None:
steps_per_noise = config['langevin_steps_per_noise']
if base_step_size is None:
base_step_size = config['langevin_base_step_size']
# Create sampler
sampler = create_annealed_sampler_from_ncsn(score_network, noise_levels,
dataset, device)
# Generate samples with trajectory tracking
samples, info = sampler.sample(num_samples, steps_per_noise,
base_step_size=base_step_size,
store_trajectory=True, store_every=subsample_steps,
verbose=False)
trajectory = info['trajectory']
noise_levels_used = info.get('noise_levels', noise_levels)
# Create animation
fig, ax = plt.subplots(figsize=FIGURE_SIZE)
ax.set_xlim(PLOT_BOUNDS[0], PLOT_BOUNDS[1])
ax.set_ylim(PLOT_BOUNDS[2], PLOT_BOUNDS[3])
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
ax.set_title('NCSM Annealed Langevin Sampling', fontsize=FONT_SIZES['title'])
# Initialize scatter plot with bigger points
scat = ax.scatter([], [], s=POINT_SIZE, alpha=0.6, c=COLORS['ncsm'], edgecolors='none')
# Add noise level text
noise_text = ax.text(0.02, 0.98, '', transform=ax.transAxes,
fontsize=FONT_SIZES['annotation'], verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
def animate(frame):
# Show normal trajectory frames
if frame < len(trajectory):
data = trajectory[frame].detach().cpu().numpy()
scat.set_offsets(data)
# Update noise level text - USE ACTUAL PARAMETERS
frames_per_noise = steps_per_noise // subsample_steps
noise_idx = min(frame // frames_per_noise,
len(noise_levels_used) - 1)
if noise_idx < len(noise_levels_used):
noise_level = noise_levels_used[noise_idx]
noise_text.set_text(f'Noise Level: {noise_level:.3f}')
else:
# Show final frame for pause frames
data = trajectory[-1].detach().cpu().numpy()
scat.set_offsets(data)
noise_text.set_text('Final Result')
return [scat, noise_text]
# Create animation with extended frames (original + pause frames)
total_frames = len(trajectory) + final_pause_frames
anim = FuncAnimation(fig, animate, frames=total_frames,
interval=interval, blit=True, repeat=True)
# Save animation to figures directory
os.makedirs('./figures', exist_ok=True)
if save_name is None:
save_name = f'ncsm_sampling_animation.gif'
save_path = os.path.join('./figures', save_name)
# Save with PillowWriter
writer = PillowWriter(fps=20)
anim.save(save_path, writer=writer)
plt.close()
print(f"Saved NCSM sampling animation: {save_path}")
return save_path
def create_sampling_animation(model_type: str,
model,
dataset,
config: Dict[str, Any],
device: torch.device,
num_samples: int = 100,
final_pause_frames: int = 20,
**kwargs) -> str:
"""
Create sampling animation based on model type.
Args:
model_type: Type of model ('ddpm', 'sm', 'ncsm')
model: Trained model
dataset: Dataset
config: Configuration dictionary
device: Device to run on
num_samples: Number of samples to generate
final_pause_frames: Number of extra frames to show final result
**kwargs: Additional arguments for specific animation types
Returns:
Path to saved animation