-
Notifications
You must be signed in to change notification settings - Fork 47
/
dnadiffusion.py
1507 lines (1240 loc) 路 52.7 KB
/
dnadiffusion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import itertools
import math
import os
import random
from functools import partial
from itertools import cycle
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torch.nn.functional as F
import torchvision.transforms as T
from accelerate import Accelerator, DistributedDataParallelKwargs
from accelerate.utils import set_seed
from einops import rearrange
from memory_efficient_attention_pytorch import Attention as EfficientAttention
from scipy.special import rel_entr
from torch import einsum, nn
from torch.optim import Adam
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
# Helper Modules
def exists(x):
return x is not None
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def cycle(dl):
while True:
yield from dl
def has_int_squareroot(num):
return (math.sqrt(num) ** 2) == num
def num_to_groups(num, divisor):
groups = num // divisor
remainder = num % divisor
arr = [divisor] * groups
if remainder > 0:
arr.append(remainder)
return arr
def convert_image_to(img_type, image):
if image.mode != img_type:
return image.convert(img_type)
return image
def l2norm(t):
return F.normalize(t, dim=-1)
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape, device=None):
batch_size = t.shape[0]
if device:
a = a.to(device)
t = t.to(device)
out = a.gather(-1, t)
result = out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
if device:
result.to(device)
return result
# Utils
class EMA: # https://github.com/dome272/Diffusion-Models-pytorch/blob/main/modules.py
def __init__(self, beta):
super().__init__()
self.beta = beta
self.step = 0
def update_model_average(self, ma_model, current_model):
for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()):
old_weight, up_weight = ma_params.data, current_params.data
ma_params.data = self.update_average(old_weight, up_weight)
def update_average(self, old, new):
if old is None:
return new
device = new.device
old = old.to(device)
return old * self.beta + (1 - self.beta) * new
def step_ema(self, ema_model, model, step_start_ema=2000):
if self.step < step_start_ema:
self.reset_parameters(ema_model, model)
self.step += 1
return
self.update_model_average(ema_model, model)
self.step += 1
def reset_parameters(self, ema_model, model):
ema_model.load_state_dict(model.state_dict())
def one_hot_encode(seq, alphabet, max_seq_len):
"""One-hot encode a sequence."""
seq_len = len(seq)
seq_array = np.zeros((max_seq_len, len(alphabet)))
for i in range(seq_len):
seq_array[i, alphabet.index(seq[i])] = 1
return seq_array
def encode(seq, alphabet):
"""Encode a sequence."""
seq_len = len(seq)
seq_array = np.zeros(len(alphabet))
for i in range(seq_len):
seq_array[alphabet.index(seq[i])] = 1
return seq_array
# Metrics
def sampling_to_metric(
number_of_samples=20,
specific_group=False,
group_number=None,
cond_weight_to_metric=0,
additional_variables=None,
):
# Sampling regions using the trained model
final_sequences = []
# for n_a in tqdm(range(number_of_samples)): # generating number_of_samples *10 sequences
for n_a in range(number_of_samples): # generating number_of_samples *10 sequences
print(n_a)
sample_bs = 10
if specific_group:
sampled = torch.from_numpy(np.array([group_number] * sample_bs))
else:
sampled = torch.from_numpy(np.random.choice(cell_types, sample_bs))
random_classes = sampled.float() # .cuda() to accelerate
if additional_variables:
random_classes = random_classes.to(additional_variables["device"])
sampled_images = sample(
classes=random_classes,
batch_size=sample_bs,
channels=1,
cond_weight=cond_weight_to_metric,
**additional_variables,
)
# sampled_images = sampled_images
for n_b, x in enumerate(sampled_images[-1]):
seq_final = f">seq_test_{n_a}_{n_b}\n" + "".join(
[nucleotides[s] for s in np.argmax(x.reshape(4, 200), axis=0)]
)
final_sequences.append(seq_final)
if group_number:
current_cell = conditional_numeric_to_tag[group_number]
save_motifs_syn = open(f"synthetic_motifs_{current_cell}.fasta", "w")
save_motifs_syn.write("\n".join(final_sequences))
save_motifs_syn.close()
os.system(
f"gimme scan synthetic_motifs_{current_cell}.fasta -p JASPAR2020_vertebrates -g hg38 > syn_results_motifs_{current_cell}.bed"
)
df_results_syn = pd.read_csv(f"syn_results_motifs_{current_cell}.bed", sep="\t", skiprows=5, header=None)
else:
save_motifs_syn = open("synthetic_motifs.fasta", "w")
save_motifs_syn.write("\n".join(final_sequences))
save_motifs_syn.close()
os.system("gimme scan synthetic_motifs.fasta -p JASPAR2020_vertebrates -g hg38 > syn_results_motifs.bed")
df_results_syn = pd.read_csv("new_syn_results_motifs.bed", sep="\t", skiprows=5, header=None)
df_results_syn["motifs"] = df_results_syn[8].apply(lambda x: x.split('motif_name "')[1].split('"')[0])
df_results_syn[0] = df_results_syn[0].apply(lambda x: "_".join(x.split("_")[:-1]))
df_motifs_count_syn = df_results_syn[[0, "motifs"]].drop_duplicates().groupby("motifs").count()
# plt.rcParams["figure.figsize"] = (30,2)
# df_motifs_count_syn.sort_values(0, ascending=False).head(50)[0].plot.bar()
# plt.show()
return df_motifs_count_syn
def compare_motif_list(df_motifs_a, df_motifs_b):
# Using KL divergence to compare motifs lists distribution
set_all_mot = set(df_motifs_a.index.values.tolist() + df_motifs_b.index.values.tolist())
create_new_matrix = []
for x in set_all_mot:
list_in = []
list_in.append(x) # adding the name
if x in df_motifs_a.index:
list_in.append(df_motifs_a.loc[x][0])
else:
list_in.append(1)
if x in df_motifs_b.index:
list_in.append(df_motifs_b.loc[x][0])
else:
list_in.append(1)
create_new_matrix.append(list_in)
df_motifs = pd.DataFrame(create_new_matrix, columns=["motif", "motif_a", "motif_b"])
df_motifs["Diffusion_seqs"] = df_motifs["motif_a"] / df_motifs["motif_a"].sum()
df_motifs["Training_seqs"] = df_motifs["motif_b"] / df_motifs["motif_b"].sum()
"""
plt.rcParams["figure.figsize"] = (3,3)
sns.regplot(x='Diffusion_seqs', y='Training_seqs',data=df_motifs)
plt.xlabel('Diffusion Seqs')
plt.ylabel('Training Seqs')
plt.title('Motifs Probs')
plt.show()
"""
kl_pq = rel_entr(df_motifs["Diffusion_seqs"].values, df_motifs["Training_seqs"].values)
return np.sum(kl_pq)
def kl_comparison_between_dataset(first_dic, second_dict):
final_comp_kl = []
for k, v in first_dic.items():
comp_array = []
for k_second in second_dict.keys():
kl_out = compare_motif_list(v, second_dict[k_second])
comp_array.append(kl_out)
final_comp_kl.append(comp_array)
return final_comp_kl
def kl_comparison_generated_sequences(
cell_list,
dict_target_cells,
additional_variables=None,
number_of_sequences_sample_per_cell=500,
):
final_comp_kl = []
use_cell_list = cell_list
for r in use_cell_list:
# print(r)
print(conditional_numeric_to_tag[r])
comp_array = []
group_compare = r
synt_df_cond = sampling_to_metric(
int(number_of_sequences_sample_per_cell / 10),
specific_group=True,
group_number=group_compare,
cond_weight_to_metric=1,
additional_variables=additional_variables,
)
for k in use_cell_list:
v = dict_target_cells[conditional_numeric_to_tag[k]]
kl_out = compare_motif_list(synt_df_cond, v)
comp_array.append(kl_out)
final_comp_kl.append(comp_array)
return final_comp_kl
def generate_heatmap(df_heat, x_label, y_label):
plt.clf()
plt.rcdefaults()
plt.rcParams["figure.figsize"] = (10, 10)
df_plot = pd.DataFrame(df_heat)
df_plot.columns = [x.split("_")[0] for x in cell_components]
df_plot.index = df_plot.columns
sns.heatmap(df_plot, cmap="Blues_r", annot=True, lw=0.1, vmax=1, vmin=0)
plt.title(f"Kl divergence \n {x_label} sequences x {y_label} sequences \n MOTIFS probabilities")
plt.xlabel(f"{x_label} Sequences \n(motifs dist)")
plt.ylabel(f"{y_label} \n (motifs dist)")
plt.grid(False)
plt.savefig(f"./graphs/{x_label}_{y_label}_kl_heatmap.png")
# wandb.log({f"Kl divergence \n {x_label} sequences x {y_label} sequences \n MOTIFS probabilities": plt})
def generate_similarity_metric():
"""Capture the syn_motifs.fasta and compare with the dataset motifs"""
seqs_file = open("synthetic_motifs.fasta").readlines()
seqs_to_hotencoder = [one_hot_encode(s.replace("\n", ""), nucleotides, 200).T for s in seqs_file if ">" not in s]
return seqs_to_hotencoder
def get_best_match(db, x_seq): # transforming in a function
return (db * x_seq).sum(1).sum(1).max()
def calculate_mean_similarity(database, input_query_seqs, seq_len=200):
final_base_max_match = np.mean([get_best_match(database, x) for x in tqdm(input_query_seqs)])
return final_base_max_match / seq_len
def generate_similarity_using_train(X_train_in):
convert_X_train = X_train_in.copy()
convert_X_train[convert_X_train == -1] = 0
generated_seqs_to_similarity = generate_similarity_metric()
return calculate_mean_similarity(convert_X_train, generated_seqs_to_similarity)
# Sampling Loop
@torch.no_grad()
def p_sample(model, x, t, t_index):
betas_t = extract(betas, t, x.shape)
sqrt_one_minus_alphas_cumprod_t = extract(sqrt_one_minus_alphas_cumprod, t, x.shape)
sqrt_recip_alphas_t = extract(sqrt_recip_alphas, t, x.shape)
# Equation 11 in the paper
# Use our model (noise predictor) to predict the mean
model_mean = sqrt_recip_alphas_t * (x - betas_t * model(x, time=t) / sqrt_one_minus_alphas_cumprod_t)
if t_index == 0:
return model_mean
else:
posterior_variance_t = extract(posterior_variance, t, x.shape)
noise = torch.randn_like(x)
# Algorithm 2 line 4:
return model_mean + torch.sqrt(posterior_variance_t) * noise
@torch.no_grad()
def p_sample_guided(
model,
x,
classes,
t,
t_index,
context_mask,
cond_weight=0.0,
betas=None,
sqrt_one_minus_alphas_cumprod=None,
sqrt_recip_alphas=None,
posterior_variance=None,
device=None,
accelerator=None,
):
# adapted from: https://openreview.net/pdf?id=qw8AKxfYbI
batch_size = x.shape[0]
# double to do guidance with
t_double = t.repeat(2).to(device)
x_double = x.repeat(2, 1, 1, 1).to(device)
betas = betas.to(device)
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device)
betas_t = extract(betas, t_double, x_double.shape, device=device)
sqrt_one_minus_alphas_cumprod_t = extract(sqrt_one_minus_alphas_cumprod, t_double, x_double.shape, device=device)
sqrt_recip_alphas_t = extract(sqrt_recip_alphas, t_double, x_double.shape, device=device)
# classifier free sampling interpolates between guided and non guided using `cond_weight`
classes_masked = classes * context_mask
classes_masked = classes_masked.type(torch.long)
if accelerator:
model = accelerator.unwrap_model(model)
model.output_attention = True
show_out_test = model(x_double, time=t_double, classes=classes_masked)
preds, cross_map_full = model(x_double, time=t_double, classes=classes_masked) # I added cross_map
model.output_attention = False
cross_map = cross_map_full[:batch_size]
eps1 = (1 + cond_weight) * preds[:batch_size]
eps2 = cond_weight * preds[batch_size:]
x_t = eps1 - eps2
# Equation 11 in the paper
# Use our model (noise predictor) to predict the mean
model_mean = sqrt_recip_alphas_t[:batch_size] * (
x - betas_t[:batch_size] * x_t / sqrt_one_minus_alphas_cumprod_t[:batch_size]
)
if t_index == 0:
return model_mean, cross_map
else:
posterior_variance_t = extract(posterior_variance, t, x.shape, device=device)
noise = torch.randn_like(x)
# Algorithm 2 line 4:
return model_mean + torch.sqrt(posterior_variance_t) * noise, cross_map
# Algorithm 2 but save all images:
@torch.no_grad()
def p_sample_loop(
model,
classes,
shape,
cond_weight,
get_cross_map=False,
timesteps=None,
device=None,
betas=None,
sqrt_one_minus_alphas_cumprod=None,
sqrt_recip_alphas=None,
posterior_variance=None,
accelerator=None,
): # to accelerate add timesteps
b = shape[0]
# start from pure noise (for each example in the batch)
img = torch.randn(shape, device=device)
imgs = []
cross_images_final = []
if classes is not None:
n_sample = classes.shape[0]
context_mask = torch.ones_like(classes).to(device)
# make 0 index unconditional
# double the batch
classes = classes.repeat(2)
context_mask = context_mask.repeat(2)
context_mask[n_sample:] = 0.0 # makes second half of batch context free
sampling_fn = partial(
p_sample_guided,
classes=classes,
cond_weight=cond_weight,
context_mask=context_mask,
betas=betas,
device=device,
sqrt_one_minus_alphas_cumprod=sqrt_one_minus_alphas_cumprod,
sqrt_recip_alphas=sqrt_recip_alphas,
posterior_variance=posterior_variance,
accelerator=accelerator,
) # to accelerate betas
else:
sampling_fn = partial(p_sample)
# for i in tqdm(reversed(range(0, timesteps)), desc='sampling loop time step', total=timesteps):
for i in reversed(range(0, timesteps)):
img, cross_matrix = sampling_fn(
model,
x=img,
t=torch.full((b,), i, device=device, dtype=torch.long),
t_index=i,
)
imgs.append(img.cpu().numpy())
cross_images_final.append(cross_matrix.cpu().numpy())
if get_cross_map:
return imgs, cross_images_final
else:
return imgs
@torch.no_grad()
def sample(
model,
image_size,
classes=None,
batch_size=16,
channels=3,
cond_weight=0,
get_cross_map=False,
timesteps=None,
device=None,
betas=None,
sqrt_one_minus_alphas_cumprod=None,
sqrt_recip_alphas=None,
posterior_variance=None,
accelerator=None,
): # to accelerate add timesteps, device , betas
return p_sample_loop(
model,
classes=classes,
shape=(batch_size, channels, 4, image_size),
cond_weight=cond_weight,
get_cross_map=get_cross_map,
timesteps=timesteps,
device=device,
betas=betas,
sqrt_one_minus_alphas_cumprod=sqrt_one_minus_alphas_cumprod,
sqrt_recip_alphas=sqrt_recip_alphas,
posterior_variance=posterior_variance,
accelerator=accelerator,
) # to accelerate add timesteps device
# Forward Diffusion
def q_sample(
x_start,
t,
sqrt_alphas_cumprod,
sqrt_one_minus_alphas_cumprod,
noise=None,
device=None,
):
if noise is None:
noise = torch.randn_like(x_start)
sqrt_alphas_cumprod_t = extract(sqrt_alphas_cumprod, t, x_start.shape).to(device)
sqrt_one_minus_alphas_cumprod_t = extract(sqrt_one_minus_alphas_cumprod, t, x_start.shape).to(device)
return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise
def p_losses(
denoise_model,
x_start,
t,
classes,
noise=None,
loss_type="l1",
p_uncond=0.1,
sqrt_alphas_cumprod_in=None,
sqrt_one_minus_alphas_cumprod_in=None,
device=None,
):
if noise is None:
noise = torch.randn_like(x_start)
x_noisy = q_sample(
x_start=x_start,
t=t,
sqrt_alphas_cumprod=sqrt_alphas_cumprod_in,
sqrt_one_minus_alphas_cumprod=sqrt_one_minus_alphas_cumprod_in,
noise=noise,
device=device,
) # this is the auto generated noise given t and Noise
context_mask = torch.bernoulli(torch.zeros(classes.shape[0]) + (1 - p_uncond)).to(device)
# mask for unconditinal guidance
classes = classes * context_mask
# nn.Embedding needs type to be long, multiplying with mask changes type
classes = classes.type(torch.long)
predicted_noise = denoise_model(x_noisy, t, classes)
if loss_type == "l1":
loss = F.l1_loss(noise, predicted_noise)
elif loss_type == "l2":
loss = F.mse_loss(noise, predicted_noise)
elif loss_type == "huber":
loss = F.smooth_l1_loss(noise, predicted_noise)
else:
raise NotImplementedError()
return loss
# Linear Beta Schedule
def linear_beta_schedule(timesteps, beta_end=0.005):
beta_start = 0.0001
return torch.linspace(beta_start, beta_end, timesteps)
class SinusoidalPositionEmbeddings(nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, time):
half_dim = self.dim // 2
embeddings = math.log(10000) / (half_dim - 1)
embeddings = torch.exp(torch.arange(half_dim) * -embeddings)
embeddings = time[:, None] * embeddings[None, :]
embeddings = torch.cat((embeddings.sin(), embeddings.cos()), dim=-1)
return embeddings
class ResBlock(nn.Module):
"""
Iniialize a residual block with two convolutions followed by batchnorm layers
"""
def __init__(self, in_size: int, hidden_size: int, out_size: int):
super().__init__()
self.conv1 = nn.Conv2d(in_size, hidden_size, 3, padding=1)
self.conv2 = nn.Conv2d(hidden_size, out_size, 3, padding=1)
self.batchnorm1 = nn.BatchNorm2d(hidden_size)
self.batchnorm2 = nn.BatchNorm2d(out_size)
def convblock(self, x):
x = F.relu(self.batchnorm1(self.conv1(x)))
x = F.relu(self.batchnorm2(self.conv2(x)))
return x
"""
Combine output with the original input
"""
def forward(self, x):
return x + self.convblock(x)
class ConvBlock_2d(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 4, padding=2),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
)
self.conv2 = nn.Sequential(
nn.Conv2d(out_channels, out_channels, 4, 1, 1),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
)
self._init_weights()
def _init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class EmbedFC(nn.Module):
def __init__(self, input_dim, emb_dim):
super().__init__()
"""
generic one layer FC NN for embedding things
"""
self.input_dim = input_dim
layers = [nn.Linear(input_dim, emb_dim), nn.GELU(), nn.Linear(emb_dim, emb_dim)]
self.model = nn.Sequential(*layers)
def forward(self, x):
return self.model(x)
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x, *args, **kwargs):
return self.fn(x, *args, **kwargs) + x
def Upsample(dim, dim_out=None):
return nn.Sequential(
nn.Upsample(scale_factor=2, mode="nearest"),
nn.Conv2d(dim, default(dim_out, dim), 3, padding=1),
)
def Downsample(dim, dim_out=None):
return nn.Conv2d(dim, default(dim_out, dim), 4, 2, 1)
class LayerNorm(nn.Module):
def __init__(self, dim):
super().__init__()
self.g = nn.Parameter(torch.ones(1, dim, 1, 1))
def forward(self, x):
eps = 1e-5 if x.dtype == torch.float32 else 1e-3
var = torch.var(x, dim=1, unbiased=False, keepdim=True)
mean = torch.mean(x, dim=1, keepdim=True)
return (x - mean) * (var + eps).rsqrt() * self.g
class PreNorm(nn.Module):
def __init__(self, dim, fn):
super().__init__()
self.fn = fn
self.norm = LayerNorm(dim)
def forward(self, x):
x = self.norm(x)
return self.fn(x)
# positional embeds
class LearnedSinusoidalPosEmb(nn.Module):
"""following @crowsonkb 's lead with learned sinusoidal pos emb"""
""" https://github.com/crowsonkb/v-diffusion-jax/blob/master/diffusion/models/danbooru_128.py#L8 """
def __init__(self, dim):
super().__init__()
assert (dim % 2) == 0
half_dim = dim // 2
self.weights = nn.Parameter(torch.randn(half_dim))
def forward(self, x):
x = rearrange(x, "b -> b 1")
freqs = x * rearrange(self.weights, "d -> 1 d") * 2 * math.pi
fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1)
fouriered = torch.cat((x, fouriered), dim=-1)
return fouriered
# building block modules
class Block(nn.Module):
def __init__(self, dim, dim_out, groups=8):
super().__init__()
self.proj = nn.Conv2d(dim, dim_out, 3, padding=1)
self.norm = nn.GroupNorm(groups, dim_out)
self.act = nn.SiLU()
def forward(self, x, scale_shift=None):
x = self.proj(x)
x = self.norm(x)
if exists(scale_shift):
scale, shift = scale_shift
x = x * (scale + 1) + shift
x = self.act(x)
return x
class ResnetBlock(nn.Module):
def __init__(self, dim, dim_out, *, time_emb_dim=None, groups=8):
super().__init__()
self.mlp = nn.Sequential(nn.SiLU(), nn.Linear(time_emb_dim, dim_out * 2)) if exists(time_emb_dim) else None
self.block1 = Block(dim, dim_out, groups=groups)
self.block2 = Block(dim_out, dim_out, groups=groups)
self.res_conv = nn.Conv2d(dim, dim_out, 1) if dim != dim_out else nn.Identity()
def forward(self, x, time_emb=None):
scale_shift = None
if exists(self.mlp) and exists(time_emb):
time_emb = self.mlp(time_emb)
time_emb = rearrange(time_emb, "b c -> b c 1 1")
scale_shift = time_emb.chunk(2, dim=1)
h = self.block1(x, scale_shift=scale_shift)
h = self.block2(h)
return h + self.res_conv(x)
class ResnetBlockClassConditioned(ResnetBlock):
def __init__(self, dim, dim_out, *, num_classes, class_embed_dim, time_emb_dim=None, groups=8):
super().__init__(
dim=dim + class_embed_dim,
dim_out=dim_out,
time_emb_dim=time_emb_dim,
groups=groups,
)
self.class_mlp = EmbedFC(num_classes, class_embed_dim)
def forward(self, x, time_emb=None, c=None):
emb_c = self.class_mlp(c)
emb_c = emb_c.view(*emb_c.shape, 1, 1)
emb_c = emb_c.expand(-1, -1, x.shape[-2], x.shape[-1])
x = torch.cat([x, emb_c], axis=1)
return super().forward(x, time_emb)
class LinearAttention(nn.Module):
def __init__(self, dim, heads=4, dim_head=32):
super().__init__()
self.scale = dim_head**-0.5
self.heads = heads
hidden_dim = dim_head * heads
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
self.to_out = nn.Sequential(nn.Conv2d(hidden_dim, dim, 1), LayerNorm(dim))
def forward(self, x):
b, c, h, w = x.shape
qkv = self.to_qkv(x).chunk(3, dim=1)
q, k, v = (rearrange(t, "b (h c) x y -> b h c (x y)", h=self.heads) for t in qkv)
q = q.softmax(dim=-2)
k = k.softmax(dim=-1)
q = q * self.scale
v = v / (h * w)
context = torch.einsum("b h d n, b h e n -> b h d e", k, v)
out = torch.einsum("b h d e, b h d n -> b h e n", context, q)
out = rearrange(out, "b h c (x y) -> b (h c) x y", h=self.heads, x=h, y=w)
return self.to_out(out)
class Attention(nn.Module):
def __init__(self, dim, heads=4, dim_head=32, scale=10):
super().__init__()
self.scale = scale
self.heads = heads
hidden_dim = dim_head * heads
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
self.to_out = nn.Conv2d(hidden_dim, dim, 1)
def forward(self, x):
b, c, h, w = x.shape
qkv = self.to_qkv(x).chunk(3, dim=1)
q, k, v = (rearrange(t, "b (h c) x y -> b h c (x y)", h=self.heads) for t in qkv)
q, k = map(l2norm, (q, k))
sim = einsum("b h d i, b h d j -> b h i j", q, k) * self.scale
attn = sim.softmax(dim=-1)
out = einsum("b h i j, b h d j -> b h i d", attn, v)
out = rearrange(out, "b h (x y) d -> b (h d) x y", x=h, y=w)
return self.to_out(out)
class CrossAttention_lucas(nn.Module):
def __init__(self, dim, heads=1, dim_head=32, scale=10):
super().__init__()
self.scale = scale
self.heads = heads
hidden_dim = dim_head * heads
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
self.to_out = nn.Conv2d(hidden_dim, dim, 1)
def forward(self, x, y):
b, c, h, w = x.shape
b_y, c_y, h_y, w_y = y.shape
qkv_x = self.to_qkv(x).chunk(3, dim=1)
qkv_y = self.to_qkv(y).chunk(3, dim=1)
q_x, k_x, v_x = (rearrange(t, "b (h c) x y -> b h c (x y)", h=self.heads) for t in qkv_x)
q_y, k_y, v_y = (rearrange(t, "b (h c) x y -> b h c (x y)", h=self.heads) for t in qkv_y)
q, k = map(l2norm, (q_x, k_y))
sim = einsum("b h d i, b h d j -> b h i j", q, k) * self.scale
attn = sim.softmax(dim=-1)
out = einsum("b h i j, b h d j -> b h i d", attn, v_y)
out = rearrange(out, "b h (x y) d -> b (h d) x y", x=h, y=w)
return self.to_out(out)
def log(t, eps=1e-20):
return torch.log(t.clamp(min=eps))
def right_pad_dims_to(x, t):
padding_dims = x.ndim - t.ndim
if padding_dims <= 0:
return t
return t.view(*t.shape, *((1,) * padding_dims))
def beta_linear_log_snr(t):
return -torch.log(expm1(1e-4 + 10 * (t**2)))
def alpha_cosine_log_snr(t, s: float = 0.008):
return -log((torch.cos((t + s) / (1 + s) * math.pi * 0.5) ** -2) - 1, eps=1e-5)
def log_snr_to_alpha_sigma(log_snr):
return torch.sqrt(torch.sigmoid(log_snr)), torch.sqrt(torch.sigmoid(-log_snr))
# Unet Model
class Unet_lucas(nn.Module):
def __init__(
self,
dim,
init_dim=None,
dim_mults=(1, 2, 4),
channels=1,
resnet_block_groups=8,
learned_sinusoidal_dim=18,
num_classes=10,
class_embed_dim=3,
output_attention=False,
):
super().__init__()
# determine dimensions
channels = 1
self.channels = channels
# if you want to do self conditioning uncomment this
input_channels = channels
self.output_attention = output_attention
init_dim = default(init_dim, dim)
self.init_conv = nn.Conv2d(input_channels, init_dim, (7, 7), padding=3)
dims = [init_dim, *(dim * m for m in dim_mults)]
# in_out = list(zip(dims[:-1], dims[1:]))
in_out = itertools.pairwise(dims)
block_klass = partial(ResnetBlock, groups=resnet_block_groups)
# time embeddings
time_dim = dim * 4
sinu_pos_emb = LearnedSinusoidalPosEmb(learned_sinusoidal_dim)
fourier_dim = learned_sinusoidal_dim + 1
self.time_mlp = nn.Sequential(
sinu_pos_emb,
nn.Linear(fourier_dim, time_dim),
nn.GELU(),
nn.Linear(time_dim, time_dim),
)
if num_classes is not None:
self.label_emb = nn.Embedding(num_classes, time_dim)
# layers
self.downs = nn.ModuleList([])
self.ups = nn.ModuleList([])
num_resolutions = len(in_out)
for ind, (dim_in, dim_out) in enumerate(in_out):
is_last = ind >= (num_resolutions - 1)
self.downs.append(
nn.ModuleList(
[
block_klass(dim_in, dim_in, time_emb_dim=time_dim),
block_klass(dim_in, dim_in, time_emb_dim=time_dim),
Residual(PreNorm(dim_in, LinearAttention(dim_in))),
Downsample(dim_in, dim_out) if not is_last else nn.Conv2d(dim_in, dim_out, 3, padding=1),
]
)
)
mid_dim = dims[-1]
self.mid_block1 = block_klass(mid_dim, mid_dim, time_emb_dim=time_dim)
self.mid_attn = Residual(PreNorm(mid_dim, Attention(mid_dim)))
self.mid_block2 = block_klass(mid_dim, mid_dim, time_emb_dim=time_dim)
for ind, (dim_in, dim_out) in enumerate(reversed(in_out)):
is_last = ind == (len(in_out) - 1)
self.ups.append(
nn.ModuleList(
[
block_klass(dim_out + dim_in, dim_out, time_emb_dim=time_dim),
block_klass(dim_out + dim_in, dim_out, time_emb_dim=time_dim),
Residual(PreNorm(dim_out, LinearAttention(dim_out))),
Upsample(dim_out, dim_in) if not is_last else nn.Conv2d(dim_out, dim_in, 3, padding=1),
]
)
)
self.final_res_block = block_klass(dim * 2, dim, time_emb_dim=time_dim)
self.final_conv = nn.Conv2d(dim, 1, 1)
self.cross_attn = EfficientAttention(
dim=200,
dim_head=64,
heads=1,
memory_efficient=True,
q_bucket_size=1024,
k_bucket_size=2048,
)
self.norm_to_cross = nn.LayerNorm(dim * 4)
def forward(self, x, time, classes, x_self_cond=None):
x = self.init_conv(x)
r = x.clone()
t_start = self.time_mlp(time)
t_mid = t_start.clone()
t_end = t_start.clone()
t_cross = t_start.clone()
if classes is not None:
t_start += self.label_emb(classes)
t_mid += self.label_emb(classes)
t_end += self.label_emb(classes)
t_cross += self.label_emb(classes)
h = []
for block1, block2, attn, downsample in self.downs:
x = block1(x, t_start)
h.append(x)
x = block2(x, t_start)
x = attn(x)
h.append(x)
x = downsample(x)
x = self.mid_block1(x, t_mid)
x = self.mid_attn(x)
x = self.mid_block2(x, t_mid)
for block1, block2, attn, upsample in self.ups:
x = torch.cat((x, h.pop()), dim=1)
x = block1(x, t_mid)
x = torch.cat((x, h.pop()), dim=1)
x = block2(x, t_mid)