Repository navigation
Expand file tree
/
Copy pathmodels.py
More file actions
1587 lines (1426 loc) · 75.2 KB
/
Copy pathmodels.py
File metadata and controls
1587 lines (1426 loc) · 75.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
import pos_encoding
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as tfd
import numpy as np
import networks
from omegaconf import open_dict
import orientations
import guidance
import os
import schedulers
# TODO apply pos-encoding refactor for Res-MLP and ViT
class DiffusionModel(nn.Module):
backbones = {"mlp": networks.ConditionalMLP, "res_mlp": networks.ResidualMLP, "unet": networks.UNet, "cond_unet": networks.CondUNet, "vit": networks.ViT}
time_encodings = {"sinusoid": pos_encoding.get_positional_encodings, "none": pos_encoding.get_none_encodings}
def __init__(self, backbone, backbone_params, in_channels, image_size, encoding_type, encoding_dim, max_diffusion_steps = 100, noise_schedule = "linear", device = "cpu", **kwargs):
super().__init__()
if backbone == "mlp" or backbone == "res_mlp":
with open_dict(backbone_params):
backbone_params.update({
"in_size": in_channels * image_size[0] * image_size[1],
"out_size": in_channels * image_size[0] * image_size[1],
"encoding_dim": encoding_dim,
"device": device,
})
elif backbone == "unet" or backbone == "cond_unet":
with open_dict(backbone_params):
backbone_params.update({
"in_channels": in_channels,
"out_channels": in_channels,
"image_shape": (image_size[0], image_size[1]),
"cond_dim": encoding_dim,
"device": device,
})
elif backbone == "vit":
with open_dict(backbone_params):
backbone_params.update({
"in_channels": in_channels,
"out_channels": in_channels,
"image_size": image_size[0],
"encoding_dim": encoding_dim,
"device": device,
})
if encoding_dim > 0:
self.encoding = DiffusionModel.time_encodings[encoding_type](max_diffusion_steps, encoding_dim).to(device)
self.encoding_dim = encoding_dim
self._reverse_model = DiffusionModel.backbones[backbone](**backbone_params)
self.in_channels = in_channels
self.max_diffusion_steps = max_diffusion_steps
self.image_size = image_size
if noise_schedule == "linear":
beta = get_linear_sched(max_diffusion_steps, kwargs["beta_1"], kwargs["beta_T"])
self._alpha_bar = torch.tensor(compute_alpha(beta), device = device, dtype=torch.float32)
self._beta = torch.tensor(beta, device = device, dtype=torch.float32)
else:
raise NotImplementedError
self._loss = nn.MSELoss(reduction = "mean")
# cache some variables:
self._sqrt_alpha_bar = torch.sqrt(self._alpha_bar)
self._sqrt_alpha_bar_complement = torch.sqrt(1 - self._alpha_bar)
self._epsilon_dist = tfd.Normal(torch.tensor([0.0], device=device), torch.tensor([1.0], device=device))
self._sigma = torch.sqrt(self._beta)
def __call__(self, x, t):
# input: x is (B, C, H, W) for images, t is (B)
# output: epsilon predictions of model
t_embed = self.compute_pos_encodings(t)
return self._reverse_model(x, t_embed).view(*x.shape)
def loss(self, x, t):
B = x.shape[0] # x is (B, C, H, W) for images
assert t.shape[0] == B and len(t.shape) == 1, "t has to have shape (B)"
# sample epsilon and generate noisy images
epsilon = self._epsilon_dist.sample(x.shape).squeeze(dim = -1) # (B, C, H, W)
x = self._sqrt_alpha_bar[t-1].view(B, *([1]*len(x.shape[1:]))) * x + self._sqrt_alpha_bar_complement[t-1].view(B, *([1]*len(x.shape[1:]))) * epsilon
x = self(x, t)
metrics = {"epsilon_theta_mean": x.detach().mean().cpu().numpy(), "epsilon_theta_std": x.detach().std().cpu().numpy()}
return self._loss(x, epsilon), metrics
def forward_samples(self, x, intermediate_every = 0):
intermediates = [x]
for t in range(self.max_diffusion_steps):
epsilon = self._epsilon_dist.sample(x.shape).squeeze(dim = -1)
x_t = self._sqrt_alpha_bar[t] * x + self._sqrt_alpha_bar_complement[t] * epsilon
if intermediate_every and t<(self.max_diffusion_steps-1) and t % intermediate_every == 0:
intermediates.append(x_t)
intermediates.append(x_t) # append final image
return intermediates
def reverse_samples(self, B, intermediate_every = 0):
# B: batch size
# intermediate_every: determines how often intermediate diffusion steps are saved and returned. 0 = no intermediates returned
batch_shape = (B, self.in_channels, self.image_size[0], self.image_size[1])
x = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) # (B, C, H, W)
intermediates = [x]
for t in range(self.max_diffusion_steps, 0 , -1):
t_vec = torch.tensor(t, device=x.device).expand(B)
z = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) if t>1 else torch.zeros_like(x)
x = (1.0/torch.sqrt(1 - self._beta[t-1])) * (x - (self._beta[t-1]/self._sqrt_alpha_bar_complement[t-1]) * self(x, t_vec))
if intermediate_every and t>1 and t % intermediate_every == 0:
intermediates.append(x)
x = x + self._sigma[t-1] * z
intermediates.append(x) # append final image
# normalize x
x_max = torch.amax(x, dim=(1,2,3), keepdim=True)
x_min = torch.amin(x, dim=(1,2,3), keepdim=True)
x_normalized = (x - x_min)/(x_max - x_min)
return x_normalized, intermediates
def compute_pos_encodings(self, t):
# t has shape (B,)
if self.encoding_dim == 0:
return None
B = t.shape[0]
encoding = self.encoding[t-1, :].view(B, self.encoding_dim)
return encoding
class CondDiffusionModel(nn.Module):
backbones = {
"mlp": networks.ConditionalMLP,
"res_mlp": networks.ResidualMLP,
"unet": networks.UNet,
"cond_unet": networks.CondUNet,
"vit": networks.ViT,
"res_gnn": networks.ResGNN,
"res_gnn_block": networks.ResGNNBlock,
"graph_unet": networks.GraphUNet,
"att_gnn": networks.AttGNN, # Current best
"graph_transformer": networks.GraphTransformer,
}
time_encodings = {
"sinusoid": pos_encoding.get_positional_encodings,
"none": pos_encoding.get_none_encodings,
}
# conditioning vec can be arbitrary
# here we use a torch_geometry object
def __init__(
self,
backbone,
backbone_params,
input_shape,
t_encoding_type,
t_encoding_dim,
max_diffusion_steps = 100,
noise_schedule = "linear",
mask_key = None,
use_mask_as_input = False,
device = "cpu",
**kwargs
):
super().__init__()
if backbone == "mlp" or backbone == "res_mlp":
self.modality = "image"
with open_dict(backbone_params):
backbone_params.update({
"in_size": np.prod(input_shape),
"out_size": np.prod(input_shape),
"encoding_dim": t_encoding_dim,
"device": device,
})
elif backbone == "unet" or backbone == "cond_unet":
self.modality = "image"
with open_dict(backbone_params):
backbone_params.update({
"in_channels": input_shape[0],
"out_channels": input_shape[0],
"image_shape": (input_shape[1], input_shape[2]),
"cond_dim": t_encoding_dim,
"device": device,
})
elif backbone == "vit":
self.modality = "image"
with open_dict(backbone_params):
backbone_params.update({
"in_channels": input_shape[0],
"out_channels": input_shape[0],
"image_size": input_shape[1],
"encoding_dim": t_encoding_dim,
"device": device,
})
elif backbone in ["res_gnn_block", "res_gnn", "graph_unet", "att_gnn", "graph_transformer"]:
self.modality = "graph"
with open_dict(backbone_params):
backbone_params.update({
"in_node_features": input_shape[1],
"out_node_features": input_shape[1],
"t_encoding_dim": t_encoding_dim,
"device": device,
"mask_key": mask_key if use_mask_as_input else None,
})
if t_encoding_dim > 0:
self.t_encoding = CondDiffusionModel.time_encodings[t_encoding_type](max_diffusion_steps, t_encoding_dim).to(device) # (N_steps, C)
self.mask_key = mask_key
self.t_encoding_dim = t_encoding_dim
self._reverse_model = CondDiffusionModel.backbones[backbone](**backbone_params)
self.input_shape = input_shape
self.max_diffusion_steps = max_diffusion_steps
if noise_schedule == "linear":
beta = get_linear_sched(max_diffusion_steps, kwargs["beta_1"], kwargs["beta_T"])
self._alpha_bar = torch.tensor(compute_alpha(beta), device = device, dtype=torch.float32) # (N_steps,)
self._beta = torch.tensor(beta, device = device, dtype=torch.float32) # (N_steps,)
else:
raise NotImplementedError
self._lossfn = nn.MSELoss(reduction = "mean")
# cache some variables:
self.device = device
self._sqrt_alpha_bar = torch.sqrt(self._alpha_bar) # (N_steps,)
self._sqrt_alpha_bar_complement = torch.sqrt(1 - self._alpha_bar)
self._epsilon_dist = tfd.Normal(torch.tensor([0.0], device=device), torch.tensor([1.0], device=device))
self._sigma = torch.sqrt(self._beta)
def __call__(self, x, cond, t):
# input: x is (B, C, H, W) for images, t is (B), cond is (1, x)
# note: 1 graph at a time
# output: epsilon predictions of model
t_embed = self.compute_pos_encodings(t)
return self._reverse_model(x, cond, t_embed).view(*x.shape)
def loss(self, x, cond, t):
B = x.shape[0] # x is (B, C, H, W) for images, (B, V, F) for graphs
assert t.shape[0] == B and len(t.shape) == 1, "t has to have shape (B)"
mask = None
if self.mask_key and self.mask_key in cond:
mask = self.get_mask(x, cond)
# sample epsilon and generate noisy images
epsilon = self._epsilon_dist.sample(x.shape).squeeze(dim = -1) # (B, C, H, W) or (B, V, F)
x_perturbed = self._sqrt_alpha_bar[t-1].view(B, *([1]*len(x.shape[1:]))) * x + self._sqrt_alpha_bar_complement[t-1].view(B, *([1]*len(x.shape[1:]))) * epsilon
# don't perturb things covered by mask
x = torch.where(mask, x, x_perturbed) if mask is not None else x_perturbed
x = self(x, cond, t)
x_masked = x.detach()[torch.logical_not(mask).expand(x.shape)] if mask is not None else x.detach()
metrics = {"epsilon_theta_mean": x_masked.mean().cpu().numpy(), "epsilon_theta_std": x_masked.std().cpu().numpy()}
return self._loss(x, epsilon, mask), metrics
def forward_samples(self, x, cond, intermediate_every = 0):
intermediates = [x]
mask = None
if self.mask_key and self.mask_key in cond:
mask = self.get_mask(x, cond)
for t in range(self.max_diffusion_steps):
epsilon = self._epsilon_dist.sample(x.shape).squeeze(dim = -1)
x_t = self._sqrt_alpha_bar[t] * x + self._sqrt_alpha_bar_complement[t] * epsilon
if mask is not None: # don't perturb things covered by mask
x_t = torch.where(mask, x, x_t)
if intermediate_every and t<(self.max_diffusion_steps-1) and t % intermediate_every == 0:
intermediates.append(x_t)
intermediates.append(x_t) # append final image
return intermediates
def reverse_samples(self, B, x_in, cond, intermediate_every = 0, mask_override = None, output_log_prob = False):
# B: batch size
# intermediate_every: determines how often intermediate diffusion steps are saved and returned. 0 = no intermediates returned
if self.modality == "image":
batch_shape = (B, *self.input_shape)
mask_shape = (1, x_in.shape[1], 1, 1)
else: # graphs
batch_shape = (B, cond.x.shape[0], self.input_shape[1])
mask_shape = (1, x_in.shape[1], 1)
x = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) # (B, C, H, W)
mask = mask_override.view(*mask_shape) if mask_override is not None else self.get_mask(x_in, cond)
x = torch.where(mask, x_in, x) if mask is not None else x
intermediates = [x]
if output_log_prob:
log_probs = torch.zeros((self.max_diffusion_steps, B,), device = x.device)
for t in range(self.max_diffusion_steps, 0 , -1):
t_vec = torch.tensor(t, device=x.device).expand(B)
z = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) if t>1 else torch.zeros_like(x)
mu = (1.0/torch.sqrt(1 - self._beta[t-1])) * (x - (self._beta[t-1]/self._sqrt_alpha_bar_complement[t-1]) * self(x, cond, t_vec))
# don't denoise things covered by mask
mu = torch.where(mask, x, mu) if mask is not None else mu
if intermediate_every and t>1 and t % intermediate_every == 0:
intermediates.append(mu.detach())
x_perturbed = mu.detach() + self._sigma[t-1] * z
# don't perturb things covered by mask
x = torch.where(mask, x, x_perturbed) if mask is not None else x_perturbed
if output_log_prob:
log_probs[t-1, :] = pi_log_prob(x, mu, self._sigma[t-1])
intermediates.append(x) # append final image
# normalize x
if self.modality == "image":
x_max = torch.amax(x, dim=(1,2,3), keepdim=True)
x_min = torch.amin(x, dim=(1,2,3), keepdim=True)
x_normalized = (x - x_min)/(x_max - x_min)
else:
x_normalized = x
if output_log_prob:
return x_normalized, intermediates, log_probs
else:
return x_normalized, intermediates
def compute_pos_encodings(self, t):
# t has shape (B,)
if self.t_encoding_dim == 0:
return None
B = t.shape[0]
encoding = self.t_encoding[t-1, :].view(B, self.t_encoding_dim)
return encoding
def get_mask(self, x, cond):
if self.modality == "graph":
if self.mask_key and self.mask_key in cond: # TODO raise error if mask key unexpectedly missing
mask = cond[self.mask_key]
B, V, F = x.shape
mask = mask.view(1, V, 1)
return mask
else:
return None
else:
raise NotImplementedError
def _loss(self, x, target, mask = None):
if mask is not None:
numel = torch.numel(mask)
squared_error = torch.square(x-target)
squared_error.masked_fill_(mask, 0)
mse = torch.mean(squared_error) * (numel / (numel - torch.sum(mask)))
return mse
else:
return self._lossfn(x, target)
class SkipDiffusionModel(CondDiffusionModel):
def __init__(
self,
max_diffusion_steps = 100,
base_diffusion_steps = 1000,
**kwargs
):
super().__init__(**kwargs, max_diffusion_steps = max_diffusion_steps)
assert base_diffusion_steps % max_diffusion_steps == 0, "new diffusion steps must divide base steps"
self.base_diffusion_steps = base_diffusion_steps
self.speedup_factor = base_diffusion_steps // max_diffusion_steps
dummy_model = CondDiffusionModel(**kwargs, max_diffusion_steps = base_diffusion_steps)
self.t_encoding = self.remap_tensor(dummy_model.t_encoding)
self._alpha_bar = self.remap_tensor(dummy_model._alpha_bar)
self._sqrt_alpha_bar = torch.sqrt(self._alpha_bar)
self._sqrt_alpha_bar_complement = torch.sqrt(1 - self._alpha_bar)
alpha = torch.zeros_like(self._alpha_bar)
alpha[1:] = self._alpha_bar[1:] / self._alpha_bar[:-1]
alpha[0] = self._alpha_bar[0]
self._beta = 1-alpha
self._sigma = torch.sqrt(self._beta)
def remap_tensor(self, x):
# Given x tensor(T_base, ...)
# Return tensor(T_new, ...) where timesteps are sampled from
in_shape = x.shape
x_reshape = x.view(self.max_diffusion_steps, self.speedup_factor, *in_shape[1:])
return x_reshape[:, -1] # Note: this is actually quite inelegant because of the endpoints, esp large speedup factors
class GuidedDiffusionModel(CondDiffusionModel):
# Uses potential-based guidance for sampling
def __init__(
self,
backbone,
backbone_params,
input_shape,
t_encoding_type,
t_encoding_dim,
legality_guidance_weight,
hpwl_guidance_weight,
guidance_step,
forward_guidance_weight,
grad_descent_steps,
grad_descent_rate,
self_recursion_steps,
max_diffusion_steps = 100,
noise_schedule = "linear",
mask_key = None,
use_mask_as_input = False,
device = "cpu",
**kwargs
):
self.legality_guidance_weight = legality_guidance_weight
self.hpwl_guidance_weight = hpwl_guidance_weight
self.guidance_step = guidance_step
self.forward_guidance_weight = forward_guidance_weight
self.grad_descent_steps = grad_descent_steps # denoted m in universal guidance paper
self.grad_descent_rate = grad_descent_rate
self.self_recursion_steps = self_recursion_steps # denoted k in universal guidance paper
super().__init__(
backbone,
backbone_params,
input_shape,
t_encoding_type,
t_encoding_dim,
max_diffusion_steps = max_diffusion_steps,
noise_schedule = noise_schedule,
mask_key = mask_key,
use_mask_as_input = use_mask_as_input,
device = device,
**kwargs
)
def reverse_samples(self, B, x_in, cond, intermediate_every = 0, mask_override = None, output_log_prob = False):
# B: batch size
# intermediate_every: determines how often intermediate diffusion steps are saved and returned. 0 = no intermediates returned
DEBUG = False # TODO change this!!
if self.modality == "image":
batch_shape = (B, *self.input_shape)
mask_shape = (1, x_in.shape[1], 1, 1)
else: # graphs
batch_shape = (B, cond.x.shape[0], self.input_shape[1])
mask_shape = (1, x_in.shape[1], 1)
x = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) # (B, C, H, W)
mask = mask_override.view(*mask_shape) if mask_override is not None else self.get_mask(x_in, cond)
x = torch.where(mask, x_in, x) if mask is not None else x
intermediates = [x]
if output_log_prob:
log_probs = torch.zeros((self.max_diffusion_steps, B,), device = x.device)
if DEBUG:
import utils
grad_norms = []
grad_norms_std = []
for t in range(self.max_diffusion_steps, 0 , -1):
x_prev = x
z = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) if t>1 else torch.zeros_like(x)
g, eps_predict = self.guidance_force_xhat(x, cond, t, mask=mask)
if output_log_prob: # need gradients on eps
t_vec = torch.tensor(t, device=x.device).expand(B)
eps_predict = self(x, cond, t_vec)
mu = (1.0/torch.sqrt(1 - self._beta[t-1])) * (x - (self._beta[t-1]/self._sqrt_alpha_bar_complement[t-1]) * eps_predict)
# don't denoise things covered by mask
mu = torch.where(mask, x_prev, mu) if mask is not None else mu
if intermediate_every and (t-1) % intermediate_every == 0: # TODO get rid of this
x_hat = (x - self._sqrt_alpha_bar_complement[t-1] * eps_predict.detach())/self._sqrt_alpha_bar[t-1]
intermediates.append(x_hat)
# intermediates.append(mu.detach())
if DEBUG and t % 200 <= 1:
# debugging
x_hat = (x - self._sqrt_alpha_bar_complement[t-1] * eps_predict.detach())/self._sqrt_alpha_bar[t-1] #(B, V, 2)
image = utils.visualize_placement(x_hat[0], cond, plot_pins=False, plot_edges=False, img_size=(256, 256))
file_idx = cond.file_idx if "file_idx" in cond else 0
utils.debug_plot_img(image, os.path.join("debug", f"xhat_{file_idx}_{t}"))
image = utils.visualize_placement(mu[0], cond, plot_pins=False, plot_edges=False, img_size=(256, 256))
utils.debug_plot_img(image, os.path.join("debug", f"beforeguidance_{file_idx}_{t}"))
if t <= self.guidance_step:
mu = mu + g
# g_norm = torch.mean(torch.norm(g, dim=2, keepdim=True))
# mu = mu + self._sqrt_alpha_bar[t-1] * (g/max(g_norm, 1)) # stronger guidance for smaller t
# if intermediate_every and (t-1) % intermediate_every == 0:
# intermediates.append(mu.detach())
if DEBUG:
g_norm = torch.norm(g, dim=2)
grad_norms.append(torch.mean(g_norm).item())
grad_norms_std.append(torch.std(g_norm).item())
if t % 200 <= 1:
# debugging
image = utils.visualize_placement(mu[0], cond, plot_pins=False, plot_edges=False, img_size=(256, 256))
utils.debug_plot_img(image, os.path.join("debug", f"afterguidance_{file_idx}_{t}"))
x = mu.detach() + self._sigma[t-1] * z
x = torch.clamp(x, -2, 2) # avoid nans TODO revert to -4, 4
# don't perturb things covered by mask
x = torch.where(mask, x_prev, x) if mask is not None else x
if output_log_prob:
log_probs[t-1, :] = pi_log_prob(x, mu, self._sigma[t-1])
if DEBUG:
utils.debug_plot_graph(grad_norms, os.path.join("debug", f"guidance_norms"), fig_title="guidance norm")
utils.debug_plot_graph(grad_norms_std, os.path.join("debug", f"guidance_norm_std"), fig_title="guidance std")
import ipdb; ipdb.set_trace()
# normalize x
if self.modality == "image":
x_max = torch.amax(x, dim=(1,2,3), keepdim=True)
x_min = torch.amin(x, dim=(1,2,3), keepdim=True)
x_normalized = (x - x_min)/(x_max - x_min)
else:
x_normalized = x
# outputs
if output_log_prob:
# TODO debug remove
print(x_in.shape)
import utils; utils.debug_mem()
return x_normalized, intermediates, log_probs
else:
return x_normalized, intermediates
def guidance_force(self, x, cond, mask=None):
# gives conditional guidance force g (see Dhariwal & Nichol 2021) NOTE this is deprecated
# mask (1, V, 1)
# x (B, V, 2)
B, V, D = x.shape
sizes = cond.x.expand(B, *cond.x.shape) # (B, V, D)
x = x + sizes/2 # centered
x_1 = x.view(B, V, 1, D)
x_2 = x.view(B, 1, V, D)
size_1 = sizes.view(B, V, 1, D)
size_2 = sizes.view(B, 1, V, D)
# compute pairwise signed distance function
delta = torch.abs(x_1 - x_2) - ((size_1 + size_2)/2) # (B, V1, V2, D)
l, max_idx = torch.max(delta, dim=-1, keepdim=True)
dl_dx = F.one_hot(max_idx.squeeze(dim=-1), num_classes=D) * torch.sign(x_1-x_2)
g = F.relu(-l) * dl_dx
mask_square = (1-torch.eye(V, dtype=g.dtype, device=g.device)).view(1, V, V, 1) # ignore self-collision
if mask is not None:
inv_mask = ~mask
mask_square = mask_square * inv_mask.view(1, 1, V, 1) * inv_mask.view(1, V, 1, 1)
g = mask_square * g
# scale by geometric mean of instance dimensions
mass_1 = torch.exp(torch.mean(torch.log(sizes), dim=-1, keepdim=True)).unsqueeze(dim=-1) # (B, V1, 1, 1)
mass_2 = mass_1.view(B, 1, V, 1) # (B, 1, V2, 1)
g = g * (mass_2/(mass_1 + mass_2)) # (B, V1, V2, D)
g_sum = g.sum(dim=-2) # (B, V1, D)
# apply boundary forces from chip canvas edges
g_bound = -F.relu(torch.abs(x) + sizes/2 - 1) * torch.sign(x) # (B, V, D)
g_bound = inv_mask * g_bound if mask is not None else g_bound
g_sum = g_sum + g_bound
return g_sum
@torch.enable_grad()
def guidance_force_xhat(self, x, cond, t, mask=None, eps_grad=False):
# gives conditional guidance force g (see Dhariwal & Nichol 2021)
# this gives the guidance term for universal backwards guidance
# mask (1, V, 1)
# x (B, V, 2)
# TODO Cache pin maps for hpwl guidance
# Note eps_grad uses more mem than just computing forward pass twice
B, V, D = x.shape
# TODO make these tunable options
legality_softmax_factor_min = 10.0
legality_softmax_factor_max = 10.0
legality_softmax_factor = legality_softmax_factor_max - (t/self.max_diffusion_steps) * (legality_softmax_factor_max-legality_softmax_factor_min)
x.requires_grad_(True)
t_vec = torch.tensor(t, device=x.device).expand(B)
try:
self.requires_grad_(eps_grad)
eps_predict = self(x, cond, t_vec)
self.requires_grad_(True)
except:
self.requires_grad_(True)
raise
x_hat = (x - self._sqrt_alpha_bar_complement[t-1] * eps_predict)/self._sqrt_alpha_bar[t-1]
# compute backward guidance on x_hat
x_hat_current = x_hat.detach().clone().requires_grad_(True)
optimizer = torch.optim.SGD((x_hat_current,), lr=self.grad_descent_rate, momentum=0.0)
# m step gradient descent TODO stop movements of objects that should be masked out
for _ in range(self.grad_descent_steps):
optimizer.zero_grad()
h_legality = self.legality_guidance_weight * guidance.legality_guidance_potential(x_hat_current, cond, mask=mask, softmax_factor=legality_softmax_factor)
h_hpwl = self.hpwl_guidance_weight * guidance.hpwl_guidance_potential(x_hat_current, cond)
h = h_legality + h_hpwl
h.sum().backward()
optimizer.step()
delta_x_hat = x_hat_current.detach() - x_hat.detach()
g = delta_x_hat * self._sqrt_alpha_bar[t-1]
eps_predict = eps_predict if eps_grad else eps_predict.detach()
if self.forward_guidance_weight > 0:
h_legality = self.legality_guidance_weight * guidance.legality_guidance_potential(x_hat, cond, mask=mask, softmax_factor=legality_softmax_factor)
h_hpwl = self.hpwl_guidance_weight * guidance.hpwl_guidance_potential(x_hat, cond)
h = h_legality + h_hpwl
h.sum().backward(retain_graph=eps_grad)
g = g.detach() - self.forward_guidance_weight * x.grad * self._sqrt_alpha_bar[t-1]
x.requires_grad_(False)
return g.detach(), eps_predict
class SkipGuidedDiffusionModel(GuidedDiffusionModel):
def __init__(
self,
max_diffusion_steps = 100,
base_diffusion_steps = 1000,
**kwargs
):
super().__init__(**kwargs, max_diffusion_steps = max_diffusion_steps)
assert base_diffusion_steps % max_diffusion_steps == 0, "new diffusion steps must divide base steps"
self.base_diffusion_steps = base_diffusion_steps
self.speedup_factor = base_diffusion_steps // max_diffusion_steps
dummy_model = GuidedDiffusionModel(**kwargs, max_diffusion_steps = base_diffusion_steps)
self.t_encoding = self.remap_tensor(dummy_model.t_encoding)
self._alpha_bar = self.remap_tensor(dummy_model._alpha_bar)
self._sqrt_alpha_bar = torch.sqrt(self._alpha_bar)
self._sqrt_alpha_bar_complement = torch.sqrt(1 - self._alpha_bar)
alpha = torch.zeros_like(self._alpha_bar)
alpha[1:] = self._alpha_bar[1:] / self._alpha_bar[:-1]
alpha[0] = self._alpha_bar[0]
self._beta = 1-alpha
self._sigma = torch.sqrt(self._beta)
def remap_tensor(self, x):
# Given x tensor(T_base, ...)
# Return tensor(T_new, ...) where timesteps are sampled from
in_shape = x.shape
x_reshape = x.view(self.max_diffusion_steps, self.speedup_factor, *in_shape[1:])
return x_reshape[:, -1] # Note: this is actually quite inelegant because of the endpoints, esp large speedup factors
class SelfCondDiffusionModel(nn.Module):
backbones = {
"mlp": networks.ConditionalMLP,
"res_mlp": networks.ResidualMLP,
"unet": networks.UNet,
"cond_unet": networks.CondUNet,
"vit": networks.ViT,
"res_gnn": networks.ResGNN,
"res_gnn_block": networks.ResGNNBlock,
"graph_unet": networks.GraphUNet,
"att_gnn": networks.AttGNN, # Current best
"graph_transformer": networks.GraphTransformer,
}
time_encodings = {
"sinusoid": pos_encoding.get_positional_encodings,
"none": pos_encoding.get_none_encodings,
}
# conditioning vec can be arbitrary
# here we use a torch_geometry object
def __init__(
self,
backbone,
backbone_params,
input_shape,
t_encoding_type,
t_encoding_dim,
self_cond_mode = "model_output",
max_diffusion_steps = 100,
noise_schedule = "linear",
mask_key = None,
use_mask_as_input = False,
device = "cpu",
**kwargs
):
super().__init__()
if backbone == "mlp" or backbone == "res_mlp":
self.modality = "image"
with open_dict(backbone_params):
backbone_params.update({
"in_size": 2 * np.prod(input_shape),
"out_size": np.prod(input_shape),
"encoding_dim": t_encoding_dim,
"device": device,
})
elif backbone == "unet" or backbone == "cond_unet":
self.modality = "image"
with open_dict(backbone_params):
backbone_params.update({
"in_channels": 2 * input_shape[0],
"out_channels": input_shape[0],
"image_shape": (input_shape[1], input_shape[2]),
"cond_dim": t_encoding_dim,
"device": device,
})
elif backbone == "vit":
self.modality = "image"
with open_dict(backbone_params):
backbone_params.update({
"in_channels": 2 * input_shape[0],
"out_channels": input_shape[0],
"image_size": input_shape[1],
"encoding_dim": t_encoding_dim,
"device": device,
})
elif backbone in ["res_gnn_block", "res_gnn", "graph_unet", "att_gnn", "graph_transformer"]:
self.modality = "graph"
with open_dict(backbone_params):
backbone_params.update({
"in_node_features": 2 * input_shape[1],
"out_node_features": input_shape[1],
"t_encoding_dim": t_encoding_dim,
"device": device,
"mask_key": mask_key if use_mask_as_input else None,
})
if t_encoding_dim > 0:
self.t_encoding = CondDiffusionModel.time_encodings[t_encoding_type](max_diffusion_steps, t_encoding_dim).to(device)
self.mask_key = mask_key
self.t_encoding_dim = t_encoding_dim
self._reverse_model = CondDiffusionModel.backbones[backbone](**backbone_params)
self.input_shape = input_shape
self.max_diffusion_steps = max_diffusion_steps
if noise_schedule == "linear":
beta = get_linear_sched(max_diffusion_steps, kwargs["beta_1"], kwargs["beta_T"])
self._alpha_bar = torch.tensor(compute_alpha(beta), device = device, dtype=torch.float32)
self._beta = torch.tensor(beta, device = device, dtype=torch.float32)
else:
raise NotImplementedError
self._lossfn = nn.MSELoss(reduction = "mean")
assert self_cond_mode in ["model_output", "x0"], "self conditioning mode must be set to either 'model_output' or 'x0'"
self.self_cond_mode = self_cond_mode
# cache some variables:
self.device = device
self._sqrt_alpha_bar = torch.sqrt(self._alpha_bar)
self._sqrt_alpha_bar_complement = torch.sqrt(1 - self._alpha_bar)
self._epsilon_dist = tfd.Normal(torch.tensor([0.0], device=device), torch.tensor([1.0], device=device))
self._sigma = torch.sqrt(self._beta)
def __call__(self, x, cond, t):
# input: x is (B, C, H, W) for images, t is (B), cond is (1, x)
# note: 1 graph at a time
# output: epsilon predictions of model
t_embed = self.compute_pos_encodings(t)
output = self._reverse_model(x, cond, t_embed)
return output
def loss(self, x, cond, t):
metrics = {}
B = x.shape[0] # x is (B, C, H, W) for images, (B, V, F) for graphs
assert t.shape[0] == B and len(t.shape) == 1, "t has to have shape (B)"
mask = None
if self.mask_key and self.mask_key in cond:
mask = self.get_mask(x, cond)
# sample epsilon and generate noisy images
epsilon = self._epsilon_dist.sample(x.shape).squeeze(dim = -1) # (B, C, H, W) or (B, V, F)
x_perturbed = self._sqrt_alpha_bar[t-1].view(B, *([1]*len(x.shape[1:]))) * x + self._sqrt_alpha_bar_complement[t-1].view(B, *([1]*len(x.shape[1:]))) * epsilon
# don't perturb things covered by mask
x_t = torch.where(mask, x, x_perturbed) if mask is not None else x_perturbed
# self-conditioning
null_condition = torch.zeros_like(x_t)
x_input = torch.concat((x_t, null_condition), dim = -1)
model_output = self(x_input, cond, t)
is_self_condition = torch.randint(2, size=(1,)).item()
if is_self_condition:
model_output.detach_()
null_cond_loss = self._loss(model_output, epsilon, mask)
if self.self_cond_mode == "model_output":
x_input = torch.concat((x_t, model_output), dim = -1)
elif self.self_cond_mode == "x0":
x_0 = (x_t.detach() - self._sqrt_alpha_bar_complement[t-1].view(B, *([1]*len(x.shape[1:]))) * model_output)/torch.sqrt(1 - self._sqrt_alpha_bar_complement[t-1]**2).view(B, *([1]*len(x.shape[1:])))
x_0 = torch.clamp(x_0, -3, 3) # avoid nans
x_0 = torch.where(mask, x, x_0) if mask is not None else x_0 # mask out ports
x_input = torch.concat((x_t, x_0), dim = -1)
model_output = self(x_input, cond, t)
train_loss = self._loss(model_output, epsilon, mask)
metrics["self_cond_loss"] = train_loss.detach().cpu().numpy()
else:
null_cond_loss = self._loss(model_output, epsilon, mask)
train_loss = null_cond_loss
output_masked = model_output.detach()[torch.logical_not(mask).expand(model_output.shape)] if mask is not None else model_output.detach()
metrics.update({
"epsilon_theta_mean": output_masked.mean().cpu().numpy(),
"epsilon_theta_std": output_masked.std().cpu().numpy(),
"null_cond_loss": null_cond_loss.detach().cpu().numpy(),
})
return train_loss, metrics
def forward_samples(self, x, cond, intermediate_every = 0):
intermediates = [x]
mask = None
if self.mask_key and self.mask_key in cond:
mask = self.get_mask(x, cond)
for t in range(self.max_diffusion_steps):
epsilon = self._epsilon_dist.sample(x.shape).squeeze(dim = -1)
x_t = self._sqrt_alpha_bar[t] * x + self._sqrt_alpha_bar_complement[t] * epsilon
if mask is not None: # don't perturb things covered by mask
x_t = torch.where(mask, x, x_t)
if intermediate_every and t<(self.max_diffusion_steps-1) and t % intermediate_every == 0:
intermediates.append(x_t)
intermediates.append(x_t) # append final image
return intermediates
def reverse_samples(self, B, x_in, cond, intermediate_every = 0, mask_override = None):
# B: batch size
# intermediate_every: determines how often intermediate diffusion steps are saved and returned. 0 = no intermediates returned
if self.modality == "image":
batch_shape = (B, *self.input_shape)
mask_shape = (1, x_in.shape[1], 1, 1)
else: # graphs
batch_shape = (B, cond.x.shape[0], self.input_shape[1])
mask_shape = (1, x_in.shape[1], 1)
x = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) # (B, C, H, W)
mask = mask_override.view(*mask_shape) if mask_override is not None else self.get_mask(x_in, cond)
x = torch.where(mask, x_in, x) if mask is not None else x
self_condition = torch.zeros_like(x)
intermediates = [x]
for t in range(self.max_diffusion_steps, 0 , -1):
t_vec = torch.tensor(t, device=x.device).expand(B)
z = self._epsilon_dist.sample(batch_shape).squeeze(dim = -1) if t>1 else torch.zeros_like(x)
x_input = torch.concat((x, self_condition), dim = -1)
eps_predict = self(x_input, cond, t_vec)
if self.self_cond_mode == "model_output":
self_condition = eps_predict
elif self.self_cond_mode == "x0":
self_condition = (x.detach() - self._sqrt_alpha_bar_complement[t-1] * eps_predict.detach())/torch.sqrt(1 - self._sqrt_alpha_bar_complement[t-1]**2)
self_condition = torch.clamp(self_condition, -3, 3) # avoid nans
self_condition = torch.where(mask, x_in, self_condition) if mask is not None else self_condition # mask out ports
else:
raise NotImplementedError
x_denoised = (1.0/torch.sqrt(1 - self._beta[t-1])) * (x - (self._beta[t-1]/self._sqrt_alpha_bar_complement[t-1]) * eps_predict)
# don't denoise things covered by mask
x = torch.where(mask, x, x_denoised) if mask is not None else x_denoised
if intermediate_every and t>1 and t % intermediate_every == 0:
intermediates.append(x)
x_perturbed = x + self._sigma[t-1] * z
# don't perturb things covered by mask
x = torch.where(mask, x, x_perturbed) if mask is not None else x_perturbed
intermediates.append(x) # append final image
# normalize x
if self.modality == "image":
x_max = torch.amax(x, dim=(1,2,3), keepdim=True)
x_min = torch.amin(x, dim=(1,2,3), keepdim=True)
x_normalized = (x - x_min)/(x_max - x_min)
else:
x_normalized = x
return x_normalized, intermediates
def compute_pos_encodings(self, t):
# t has shape (B,)
if self.t_encoding_dim == 0:
return None
B = t.shape[0]
encoding = self.t_encoding[t-1, :].view(B, self.t_encoding_dim)
return encoding
def get_mask(self, x, cond):
if self.modality == "graph":
if self.mask_key and self.mask_key in cond:
mask = cond[self.mask_key]
B, V, F = x.shape
mask = mask.view(1, V, 1)
return mask
else:
return None
else:
raise NotImplementedError
def _loss(self, x, target, mask = None):
if mask is not None:
numel = torch.numel(mask)
squared_error = torch.square(x-target)
squared_error.masked_fill_(mask, 0)
mse = torch.mean(squared_error) * (numel / (numel - torch.sum(mask)))
return mse
else:
return self._lossfn(x, target)
class MixedDiffusionModel(nn.Module):
"""
Diffusion model for mixing continuous and discrete spaces
Specific to graph modality
Continuous input has shape (V, F_cont), discrete input has shape (V, F_disc)
"""
backbones = {
"att_gnn": networks.AttGNN, # Current best
"graph_transformer": networks.GraphTransformer,
}
time_encodings = {
"sinusoid": pos_encoding.get_positional_encodings,
"none": pos_encoding.get_none_encodings,
}
def __init__(
self,
backbone,
backbone_params,
input_cont_dim,
input_disc_dim,
t_encoding_type,
t_encoding_dim,
self_cond_mode = "model_output",
discrete_prediction = "x0",
max_diffusion_steps = 100,
noise_schedule = "linear",
mask_key = None,
use_mask_as_input = False,
device = "cpu",
**kwargs
):
super().__init__()
if backbone in ["att_gnn", "graph_transformer"]:
with open_dict(backbone_params):
backbone_params.update({
"in_node_features": 2 * (input_cont_dim + input_disc_dim), # for self-conditioning
"out_node_features": input_cont_dim + input_disc_dim,
"t_encoding_dim": t_encoding_dim,
"device": device,
"mask_key": mask_key if use_mask_as_input else None,
})
if t_encoding_dim > 0:
self.t_encoding = CondDiffusionModel.time_encodings[t_encoding_type](max_diffusion_steps, t_encoding_dim).to(device)
self.mask_key = mask_key
self.t_encoding_dim = t_encoding_dim
self._reverse_model = CondDiffusionModel.backbones[backbone](**backbone_params)
self.input_cont_dim = input_cont_dim
self.input_disc_dim = input_disc_dim
self.max_diffusion_steps = max_diffusion_steps
if noise_schedule == "linear":
beta = get_linear_sched(max_diffusion_steps, kwargs["beta_1"], kwargs["beta_T"])
self._alpha_bar = torch.tensor(compute_alpha(beta), device = device, dtype=torch.float32)
self._beta = torch.tensor(beta, device = device, dtype=torch.float32)
else:
raise NotImplementedError
self._lossfn = nn.MSELoss(reduction = "mean")
if self_cond_mode is not None:
assert self_cond_mode in ["model_output", "x0", "none"], "self conditioning mode must be set to either 'model_output' or 'x0' or none"
self.self_cond_mode = self_cond_mode
assert discrete_prediction in ["x0", "epsilon"], "discrete_prediction must be either 'x0' or 'epsilon'"
self.discrete_prediction = discrete_prediction
# cache some variables:
self.device = device
self._sqrt_alpha_bar = torch.sqrt(self._alpha_bar)
self._sqrt_alpha_bar_complement = torch.sqrt(1 - self._alpha_bar)
self._epsilon_dist = tfd.Normal(torch.tensor([0.0], device=device), torch.tensor([1.0], device=device))
self._sigma = torch.sqrt(self._beta)
def __call__(self, x_cont, x_disc, cond, t):
"""
input: x is (B, V, F) for graphs (for continuous and disc inputs), t is (B), cond is pyG data object.
note: 1 graph at a time
output: epsilon predictions of model
"""
t_embed = self.compute_t_encodings(t)
x_combined = self.combine_inputs(x_cont, x_disc)
output = self._reverse_model(x_combined, cond, t_embed)
output_cont, output_disc = self.split_inputs(output)
return output_cont, output_disc
def loss(self, x_cont, x_disc, cond, t):
"""
x_cont: (B, V, F_cont)
x_disc: (B, V, F_disc)
cond: PyG Data object containing x (B, V), edge_index, edge_attr, mask
t: (B)
"""
metrics = {}
B, V, _ = x_cont.shape # x is (B, V, F) for graphs
assert t.shape[0] == B and len(t.shape) == 1, "t has to have shape (B)"
mask = None
if self.mask_key and self.mask_key in cond:
mask = self.get_mask(cond)
coeff_shape = [B] + [1] * len(x_cont.shape[1:]) # for reshaping alpha_bar, etc.
# sample epsilon and generate noisy images
epsilon_cont = self._epsilon_dist.sample(x_cont.shape).squeeze(dim = -1) # (B, V, F)
epsilon_disc = self._epsilon_dist.sample(x_disc.shape).squeeze(dim = -1) # (B, V, F)
x_perturbed_cont = self._sqrt_alpha_bar[t-1].view(*coeff_shape) * x_cont + self._sqrt_alpha_bar_complement[t-1].view(*coeff_shape) * epsilon_cont
x_perturbed_disc = self._sqrt_alpha_bar[t-1].view(*coeff_shape) * x_disc + self._sqrt_alpha_bar_complement[t-1].view(*coeff_shape) * epsilon_disc
# don't perturb things covered by mask
x_t_cont = torch.where(mask, x_cont, x_perturbed_cont) if mask is not None else x_perturbed_cont
x_t_disc = torch.where(mask, x_disc, x_perturbed_disc) if mask is not None else x_perturbed_disc
# self-conditioning TODO check for edge cases in terms of t?
null_condition_cont = torch.zeros_like(x_t_cont)
null_condition_disc = torch.zeros_like(x_t_disc)
x_input_cont = torch.concat((x_t_cont, null_condition_cont), dim = -1)
x_input_disc = torch.concat((x_t_disc, null_condition_disc), dim = -1)
model_output_cont, model_output_disc = self(x_input_cont, x_input_disc, cond, t)
# prediction target for continuous is epsilon, for discrete is x0
target_cont = epsilon_cont
target_disc = x_disc if self.discrete_prediction=="x0" else epsilon_disc
# debugging TODO remove or refactor
bitwise_loss = self._loss(model_output_disc, target_disc, mask, debug=True).detach().cpu().numpy() # (3)
if self.discrete_prediction == "x0":
pred_x0 = model_output_disc
else:
pred_x0 = (x_t_disc - self._sqrt_alpha_bar_complement[t-1].view(*coeff_shape) * model_output_disc.detach())/torch.sqrt(1 - self._sqrt_alpha_bar_complement[t-1]**2).view(*coeff_shape)
bitwise_accuracies = torch.clamp(torch.sgn(pred_x0 * x_disc), min=0).mean(dim=1).mean(dim=0).detach().cpu().numpy() # check sign equality
metrics.update({
"bit_0_loss": bitwise_loss[0],
"bit_1_loss": bitwise_loss[1],