forked from gwang-kim/DiffusionCLIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diffusionclip.py
1269 lines (1101 loc) · 66.7 KB
/
diffusionclip.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 time
# copyy
from glob import glob
from tqdm import tqdm
import os
import numpy as np
import cv2
import pickle
from PIL import Image
import torch
from torch import nn
import torchvision.utils as tvu
from matplotlib import pyplot as plt
from models.ddpm.diffusion import DDPM
from models.improved_ddpm.script_util import i_DDPM
from utils.text_dic import SRC_TRG_TXT_DIC
from utils.diffusion_utils import get_beta_schedule, denoising_step
from losses import id_loss
from losses.clip_loss import CLIPLoss
from datasets.data_utils import get_dataset, get_dataloader
from configs.paths_config import DATASET_PATHS, MODEL_PATHS, HYBRID_MODEL_PATHS, HYBRID_CONFIG
from datasets.imagenet_dic import IMAGENET_DIC
from utils.align_utils import run_alignment
class DiffusionCLIP(object):
def __init__(self, args, config, device=None):
self.args = args
self.config = config
if device is None:
device = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu")
self.device = device
self.model_var_type = config.model.var_type
betas = get_beta_schedule(
beta_start=config.diffusion.beta_start,
beta_end=config.diffusion.beta_end,
num_diffusion_timesteps=config.diffusion.num_diffusion_timesteps
)
self.betas = torch.from_numpy(betas).float().to(self.device)
self.num_timesteps = betas.shape[0]
alphas = 1.0 - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
posterior_variance = betas * \
(1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
if self.model_var_type == "fixedlarge":
self.logvar = np.log(np.append(posterior_variance[1], betas[1:]))
elif self.model_var_type == 'fixedsmall':
self.logvar = np.log(np.maximum(posterior_variance, 1e-20))
if self.args.edit_attr is None:
self.src_txts = self.args.src_txts
self.trg_txts = self.args.trg_txts
else:
self.src_txts = SRC_TRG_TXT_DIC[self.args.edit_attr][0]
self.trg_txts = SRC_TRG_TXT_DIC[self.args.edit_attr][1]
self.finetune_class_name = args.finetune_class_name
self.finetune_region = args.finetune_region
def clip_finetune(self):
print(self.args.exp)
print(f' {self.src_txts}')
print(f'-> {self.trg_txts}')
# ----------- Model -----------#
if self.config.data.dataset == "LSUN":
if self.config.data.category == "bedroom":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/bedroom.ckpt"
elif self.config.data.category == "church_outdoor":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/church_outdoor.ckpt"
elif self.config.data.dataset == "CelebA_HQ":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/celeba_hq.ckpt"
elif self.config.data.dataset == "AFHQ":
pass
else:
raise ValueError
if self.config.data.dataset in ["CelebA_HQ", "LSUN"]:
model = DDPM(self.config)
if self.args.model_path:
init_ckpt = torch.load(self.args.model_path)
else:
init_ckpt = torch.hub.load_state_dict_from_url(url, map_location=self.device)
learn_sigma = False
print("Original diffusion Model loaded.")
elif self.config.data.dataset in ["FFHQ", "AFHQ"]:
model = i_DDPM(self.config.data.dataset)
if self.args.model_path:
init_ckpt = torch.load(self.args.model_path)
else:
init_ckpt = torch.load(MODEL_PATHS[self.config.data.dataset])
learn_sigma = True
print("Improved diffusion Model loaded.")
else:
print('Not implemented dataset')
raise ValueError
model.load_state_dict(init_ckpt)
model.to(self.device)
model = torch.nn.DataParallel(model)
# ----------- Optimizer and Scheduler -----------#
print(f"Setting optimizer with lr={self.args.lr_clip_finetune}")
optim_ft = torch.optim.Adam(model.parameters(), weight_decay=0, lr=self.args.lr_clip_finetune)
init_opt_ckpt = optim_ft.state_dict()
scheduler_ft = torch.optim.lr_scheduler.StepLR(optim_ft, step_size=1, gamma=self.args.sch_gamma)
init_sch_ckpt = scheduler_ft.state_dict()
# ----------- Loss -----------#
print("Loading losses")
clip_loss_func = CLIPLoss(
self.device,
lambda_direction=1,
lambda_patch=0,
lambda_global=0,
lambda_manifold=0,
lambda_texture=0,
clip_model=self.args.clip_model_name)
id_loss_func = id_loss.IDLoss().to(self.device).eval()
# ----------- Precompute Latents -----------#
print("Prepare identity latent")
seq_inv = np.linspace(0, 1, self.args.n_inv_step) * self.args.t_0
seq_inv = [int(s) for s in list(seq_inv)]
seq_inv_next = [-1] + list(seq_inv[:-1])
n = self.args.bs_train
img_lat_pairs_dic = {}
for mode in ['train', 'test']:
img_lat_pairs = []
pairs_path = os.path.join('precomputed/',
f'{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
print(pairs_path)
if os.path.exists(pairs_path):
print(f'{mode} pairs exists')
img_lat_pairs_dic[mode] = torch.load(pairs_path)
for step, (x0, x_id, x_lat) in enumerate(img_lat_pairs_dic[mode]):
tvu.save_image((x0 + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_0_orig.png'))
tvu.save_image((x_id + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_1_rec_ninv{self.args.n_inv_step}.png'))
if step == self.args.n_precomp_img - 1:
break
continue
else:
train_dataset, test_dataset = get_dataset(self.config.data.dataset, DATASET_PATHS, self.config)
loader_dic = get_dataloader(train_dataset, test_dataset, bs_train=self.args.bs_train,
num_workers=self.config.data.num_workers)
loader = loader_dic[mode]
for step, img in enumerate(loader):
x0 = img.to(self.config.device)
tvu.save_image((x0 + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_0_orig.png'))
x = x0.clone()
model.eval()
with torch.no_grad():
with tqdm(total=len(seq_inv), desc=f"Inversion process {mode} {step}") as progress_bar:
for it, (i, j) in enumerate(zip((seq_inv_next[1:]), (seq_inv[1:]))):
t = (torch.ones(n) * i).to(self.device)
t_prev = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_prev, models=model,
logvars=self.logvar,
sampling_type='ddim',
b=self.betas,
eta=0,
learn_sigma=learn_sigma)
progress_bar.update(1)
x_lat = x.clone()
tvu.save_image((x_lat + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_1_lat_ninv{self.args.n_inv_step}.png'))
with tqdm(total=len(seq_inv), desc=f"Generative process {mode} {step}") as progress_bar:
for it, (i, j) in enumerate(zip(reversed((seq_inv)), reversed((seq_inv_next)))):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
learn_sigma=learn_sigma)
progress_bar.update(1)
img_lat_pairs.append([x0, x.detach().clone(), x_lat.detach().clone()])
tvu.save_image((x + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_1_rec_ninv{self.args.n_inv_step}.png'))
if step == self.args.n_precomp_img - 1:
break
img_lat_pairs_dic[mode] = img_lat_pairs
pairs_path = os.path.join('precomputed/',
f'{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
torch.save(img_lat_pairs, pairs_path)
# ----------- Finetune Diffusion Models -----------#
print("Start finetuning")
print(f"Sampling type: {self.args.sample_type.upper()} with eta {self.args.eta}")
if self.args.n_train_step != 0:
seq_train = np.linspace(0, 1, self.args.n_train_step) * self.args.t_0
seq_train = [int(s) for s in list(seq_train)]
print('Uniform skip type')
else:
seq_train = list(range(self.args.t_0))
print('No skip')
seq_train_next = [-1] + list(seq_train[:-1])
seq_test = np.linspace(0, 1, self.args.n_test_step) * self.args.t_0
seq_test = [int(s) for s in list(seq_test)]
seq_test_next = [-1] + list(seq_test[:-1])
for src_txt, trg_txt in zip(self.src_txts, self.trg_txts):
print(f"CHANGE {src_txt} TO {trg_txt}")
model.module.load_state_dict(init_ckpt)
optim_ft.load_state_dict(init_opt_ckpt)
scheduler_ft.load_state_dict(init_sch_ckpt)
clip_loss_func.target_direction = None
# ----------- Train -----------#
for it_out in range(self.args.n_iter):
exp_id = os.path.split(self.args.exp)[-1]
save_name = f'checkpoint/{exp_id}_{trg_txt.replace(" ", "_")}-{it_out}.pth'
if self.args.do_train:
if os.path.exists(save_name):
print(f'{save_name} already exists.')
model.module.load_state_dict(torch.load(save_name))
continue
else:
for step, (x0, x_id, x_lat) in enumerate(img_lat_pairs_dic['train']):
model.train()
time_in_start = time.time()
optim_ft.zero_grad()
x = x_lat.clone()
with tqdm(total=len(seq_train), desc=f"CLIP iteration") as progress_bar:
for t_it, (i, j) in enumerate(zip(reversed(seq_train), reversed(seq_train_next))):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
eta=self.args.eta,
learn_sigma=learn_sigma)
progress_bar.update(1)
loss_clip = (2 - clip_loss_func(x0, src_txt, x, trg_txt)) / 2
loss_clip = -torch.log(loss_clip)
loss_id = torch.mean(id_loss_func(x0, x))
loss_l1 = nn.L1Loss()(x0, x)
loss = self.args.clip_loss_w * loss_clip + self.args.id_loss_w * loss_id + self.args.l1_loss_w * loss_l1
loss.backward()
optim_ft.step()
print(f"CLIP {step}-{it_out}: loss_id: {loss_id:.3f}, loss_clip: {loss_clip:.3f}")
if self.args.save_train_image:
tvu.save_image((x + 1) * 0.5, os.path.join(self.args.image_folder,
f'train_{step}_2_clip_{trg_txt.replace(" ", "_")}_{it_out}_ngen{self.args.n_train_step}.png'))
time_in_end = time.time()
print(f"Training for 1 image takes {time_in_end - time_in_start:.4f}s")
if step == self.args.n_train_img - 1:
break
if it_out == 0 or it_out == self.args.n_iter - 1:
if isinstance(model, nn.DataParallel):
torch.save(model.module.state_dict(), save_name)
else:
torch.save(model.state_dict(), save_name)
print(f'Model {save_name} is saved.')
scheduler_ft.step()
# ----------- Eval -----------#
if self.args.do_test:
if not self.args.do_train:
print(save_name)
model.module.load_state_dict(torch.load(save_name))
model.eval()
img_lat_pairs = img_lat_pairs_dic[mode]
for step, (x0, x_id, x_lat) in enumerate(img_lat_pairs):
with torch.no_grad():
x = x_lat
with tqdm(total=len(seq_test), desc=f"Eval iteration") as progress_bar:
for i, j in zip(reversed(seq_test), reversed(seq_test_next)):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
eta=self.args.eta,
learn_sigma=learn_sigma)
progress_bar.update(1)
print(f"Eval {step}-{it_out}")
tvu.save_image((x + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_2_clip_{trg_txt.replace(" ", "_")}_{it_out}_ngen{self.args.n_test_step}.png'))
if step == self.args.n_test_img - 1:
break
def clip_finetune_eff(self):
print(self.args.exp)
print(f' {self.src_txts}')
print(f'-> {self.trg_txts}')
# ----------- Model -----------#
if self.config.data.dataset == "LSUN":
if self.config.data.category == "bedroom":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/bedroom.ckpt"
elif self.config.data.category == "church_outdoor":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/church_outdoor.ckpt"
elif self.config.data.dataset == "CelebA_HQ":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/celeba_hq.ckpt"
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
pass
else:
raise ValueError
if self.config.data.dataset in ["CelebA_HQ", "LSUN"]:
model = DDPM(self.config)
if self.args.model_path:
init_ckpt = torch.load(self.args.model_path)
else:
init_ckpt = torch.hub.load_state_dict_from_url(url, map_location=self.device)
learn_sigma = False
print("Original diffusion Model loaded.")
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
print('FORCING IMAGNET DDPM CREATION')
# model = i_DDPM(self.config.data.dataset)
model = i_DDPM("IMAGENET")
if self.args.model_path:
init_ckpt = torch.load(self.args.model_path)
else:
init_ckpt = torch.load(MODEL_PATHS[self.config.data.dataset])
learn_sigma = True
print("Improved diffusion Model loaded.")
else:
print('Not implemented dataset')
raise ValueError
model.load_state_dict(init_ckpt)
model.to(self.device)
model = torch.nn.DataParallel(model)
# ----------- Optimizer and Scheduler -----------#
print(f"Setting optimizer with lr={self.args.lr_clip_finetune}")
optim_ft = torch.optim.Adam(model.parameters(), weight_decay=0, lr=self.args.lr_clip_finetune)
# optim_ft = torch.optim.SGD(model.parameters(), weight_decay=0, lr=self.args.lr_clip_finetune)#, momentum=0.9)
init_opt_ckpt = optim_ft.state_dict()
scheduler_ft = torch.optim.lr_scheduler.StepLR(optim_ft, step_size=1, gamma=self.args.sch_gamma)
init_sch_ckpt = scheduler_ft.state_dict()
# ----------- Loss -----------#
print("Loading losses")
clip_loss_func = CLIPLoss(
self.device,
lambda_direction=1,
lambda_patch=0,
lambda_global=0,
lambda_manifold=0,
lambda_texture=0,
clip_model=self.args.clip_model_name)
id_loss_func = id_loss.IDLoss().to(self.device).eval()
# ----------- Precompute Latents -----------#
print("Prepare identity latent")
seq_inv = np.linspace(0, 1, self.args.n_inv_step) * self.args.t_0
seq_inv = [int(s) for s in list(seq_inv)]
seq_inv_next = [-1] + list(seq_inv[:-1])
n = self.args.bs_train
img_lat_pairs_dic = {}
modes = ['train', 'test']
for mode in ['train']:
img_lat_pairs = []
if self.args.edit_attr in ['female', 'male']:
self.config.data.dataset = 'GENDER'
self.config.data.category = 'GENDER'
if self.args.edit_attr == 'female':
pairs_path = os.path.join('precomputed/',
f'{self.config.data.category}_male_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
else:
pairs_path = os.path.join('precomputed/',
f'{self.config.data.category}_female_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
elif self.config.data.dataset == "IMAGENET":
if self.args.target_class_num is not None:
pairs_path = os.path.join('precomputed/',
f'{self.config.data.category}_{IMAGENET_DIC[str(self.args.target_class_num)][1]}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
else:
pairs_path = os.path.join('precomputed/',
f'{self.args.data_override}_{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
else:
# pairs_path = os.path.join('precomputed/',
# f'{self.args.data_override}_{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
pairs_path = os.path.join('precomputed/',f'{self.args.model_save_name}_{self.args.param_set}.pth')
print(pairs_path)
if os.path.exists(pairs_path):
print(f'{mode} pairs exists')
img_lat_pairs_dic[mode] = torch.load(pairs_path, map_location=torch.device('cpu'))
for step, (x0, x_id, x_lat) in enumerate(img_lat_pairs_dic[mode]):
tvu.save_image((x0 + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_0_orig.png'))
tvu.save_image((x_id + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_1_rec_ninv{self.args.n_inv_step}.png'))
if step == self.args.n_precomp_img - 1:
break
continue
else:
if self.args.edit_attr == 'female':
train_dataset, test_dataset = get_dataset(self.config.data.dataset, DATASET_PATHS, self.config,
gender='male')
elif self.args.edit_attr == 'male':
train_dataset, test_dataset = get_dataset(self.config.data.dataset, DATASET_PATHS, self.config,
gender='female')
elif self.args.data_override:
print(f'FORCING TO USE DATASET {self.args.data_override} for FINETUNE')
if self.args.data_override == 'GEODE':
train_dataset, test_dataset = get_dataset(self.args.data_override, DATASET_PATHS, self.config,
target_class_num=self.args.target_class_num, \
class_name=self.finetune_class_name, region=self.finetune_region)
else:
train_dataset, test_dataset = get_dataset(self.args.data_override, DATASET_PATHS, self.config,
target_class_num=self.args.target_class_num, class_name=self.finetune_class_name)
else:
print('default to AFHQ')
train_dataset, test_dataset = get_dataset('AFHQ', DATASET_PATHS, self.config,
target_class_num=self.args.target_class_num, class_name=self.finetune_class_name)
loader_dic = get_dataloader(train_dataset, test_dataset, bs_train=self.args.bs_train,
num_workers=self.config.data.num_workers)
loader = loader_dic[mode]
print(len(loader), 'images in loader')
for step, img in enumerate(loader):
x0 = img.to(self.config.device)
# tvu.save_image((x0 + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_0_orig.png'))
print('image shape', x0.shape)
x = x0.clone()
model.eval()
time_s = time.time()
with torch.no_grad():
with tqdm(total=len(seq_inv), desc=f"Inversion process {mode} {step}") as progress_bar:
for it, (i, j) in enumerate(zip((seq_inv_next[1:]), (seq_inv[1:]))):
t = (torch.ones(n) * i).to(self.device)
t_prev = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_prev, models=model,
logvars=self.logvar,
sampling_type='ddim',
b=self.betas,
eta=0,
learn_sigma=learn_sigma)
progress_bar.update(1)
time_e = time.time()
print(f'{time_e - time_s} seconds')
x_lat = x.clone()
print('x lat shape', x_lat.shape)
# tvu.save_image((x_lat + 1) * 0.5, os.path.join(self.args.image_folder,
# f'{mode}_{step}_1_lat_ninv{self.args.n_inv_step}.png'))
with tqdm(total=len(seq_inv), desc=f"Generative process {mode} {step}") as progress_bar:
time_s = time.time()
for it, (i, j) in enumerate(zip(reversed((seq_inv)), reversed((seq_inv_next)))):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
learn_sigma=learn_sigma)
progress_bar.update(1)
time_e = time.time()
print(f'{time_e - time_s} seconds')
img_lat_pairs.append([x0, x.detach().clone(), x_lat.detach().clone()])
tvu.save_image((x + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_1_rec_ninv{self.args.n_inv_step}.png'))
if step == self.args.n_precomp_img - 1:
break
img_lat_pairs_dic[mode] = img_lat_pairs
# pairs_path = os.path.join('precomputed/',
# f'{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
torch.save(img_lat_pairs, pairs_path)
# ----------- Finetune Diffusion Models -----------#
print("Start finetuning")
print(f"Sampling type: {self.args.sample_type.upper()} with eta {self.args.eta}")
if self.args.n_train_step != 0:
seq_train = np.linspace(0, 1, self.args.n_train_step) * self.args.t_0
seq_train = [int(s) for s in list(seq_train)]
print('Uniform skip type')
else:
seq_train = list(range(self.args.t_0))
print('No skip')
seq_train_next = [-1] + list(seq_train[:-1])
seq_test = np.linspace(0, 1, self.args.n_test_step) * self.args.t_0
seq_test = [int(s) for s in list(seq_test)]
seq_test_next = [-1] + list(seq_test[:-1])
for src_txt, trg_txt in zip(self.src_txts, self.trg_txts):
print(f"CHANGE {src_txt} TO {trg_txt}")
model.module.load_state_dict(init_ckpt)
optim_ft.load_state_dict(init_opt_ckpt)
scheduler_ft.load_state_dict(init_sch_ckpt)
clip_loss_func.target_direction = None
iter_losses = []
# ----------- Train -----------#
for it_out in range(self.args.n_iter):
iter_loss = 0
last_loss = 0
exp_id = os.path.split(self.args.exp)[-1]
print('save name parts', exp_id, trg_txt, it_out)
save_name = f'checkpoint/{exp_id}_{trg_txt.replace(" ", "_")}-{it_out}.pth'
if self.args.model_save_name:
# save_name = f'checkpoint/{self.args.model_save_name}-{it_out}.pth'
# full_model_save_name = f'checkpoint/{self.args.model_save_name}-{it_out}.pt'
save_name = f'checkpoint/{self.args.model_save_name}_{self.args.param_set}.pth'
full_model_save_name = f'checkpoint/{self.args.model_save_name}_{self.args.param_set}.pt'
if self.args.do_train:
if os.path.exists(save_name):
print(f'{save_name} already exists.')
model.module.load_state_dict(torch.load(save_name))
continue
else:
for step, (x0, _, x_lat) in enumerate(img_lat_pairs_dic['train']):
model.train()
time_in_start = time.time()
optim_ft.zero_grad()
x = x_lat.clone().to(self.device)
x0 = x0.to(self.device)
with tqdm(total=len(seq_train), desc=f"CLIP iteration") as progress_bar:
for t_it, (i, j) in enumerate(zip(reversed(seq_train), reversed(seq_train_next))):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x, x0_t = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
eta=self.args.eta,
learn_sigma=learn_sigma,
out_x0_t=True)
progress_bar.update(1)
x = x.detach().clone()
loss_clip = -torch.log((2 - clip_loss_func(x0, src_txt, x0_t, trg_txt)) / 2)
loss_l1 = nn.L1Loss()(x0, x0_t)
loss = self.args.clip_loss_w * loss_clip + self.args.l1_loss_w * loss_l1
# if self.args.id_loss_w != 0:
# print('using ID loss')
# loss_id = torch.mean(id_loss_func(x0, x))
# loss += self.args.id_loss_w * loss_id
loss.backward()
iter_loss += loss
if it_out == self.args.n_iter - 1:
last_loss += loss
optim_ft.step()
for p in model.module.parameters():
p.grad = None
print(f"CLIP {step}-{it_out}: loss_clip: {loss_clip:.3f}")
# break
if self.args.save_train_image:
extra = "ID" if self.args.id_loss_w > 0 else f"{trg_txt.replace(" ", "_")}{trg_txt.replace(" ", "_")}"
save_train_name = f'{self.args.data_override}_{extra})train_{step}_{it_out}_ngen_{self.args.n_train_step}.png'
tvu.save_image((x0_t + 1) * 0.5, os.path.join(self.args.image_folder, save_train_name))
time_in_end = time.time()
print(f"Training for 1 image takes {time_in_end - time_in_start:.4f}s")
if step == self.args.n_train_img - 1:
break
# Tracking Loss for Plot
iter_losses.append(iter_loss.item())
print('appending to loss,', iter_loss.item())
if it_out == self.args.n_iter-1:
iter_losses.append(last_loss.item())
if it_out == self.args.n_iter-1:
if isinstance(model, nn.DataParallel):
torch.save(model.module.state_dict(), save_name)
else:
torch.save(model.state_dict(), save_name)
torch.save(model, full_model_save_name) # same complete model obj for loading later
print(f'Model {save_name} is saved.')
scheduler_ft.step()
# ----------- Eval -----------#
if self.args.do_test:
if not self.args.do_train:
print(save_name)
model.module.load_state_dict(torch.load(save_name))
model.eval()
img_lat_pairs = img_lat_pairs_dic[mode]
for step, (x0, x_id, x_lat) in enumerate(img_lat_pairs):
with torch.no_grad():
x = x_lat.clone().to(self.device)
x0 = x0.to(self.device)
with tqdm(total=len(seq_test), desc=f"Eval iteration") as progress_bar:
for i, j in zip(reversed(seq_test), reversed(seq_test_next)):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
eta=self.args.eta,
learn_sigma=learn_sigma)
progress_bar.update(1)
print(f"Eval {step}-{it_out}")
tvu.save_image((x + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_2_clip_{trg_txt.replace(" ", "_")}_{it_out}_ngen{self.args.n_test_step}.png'))
if step == self.args.n_test_img - 1:
break
pickle.dump(iter_losses,f'plots/losses_{f'{self.args.data_override}_{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth'}')
# iter_values = np.arange(0, len(iter_losses))
# plt.plot(iter_values, iter_losses)
# plt.title('Loss vs Fine-Tuning Iterations')
# plt.xlabel("Fine Tuning Iterations")
# plt.ylabel("Loss")
# plt.savefig(f'plots/plot_{self.args.save_name}.png')
def clip_latent_optim(self):
# ----------- Data -----------#
n = 1
if self.args.align_face and self.config.data.dataset in ["FFHQ", "CelebA_HQ"]:
try:
img = run_alignment(self.args.img_path, output_size=self.config.data.image_size)
except:
img = Image.open(self.args.img_path).convert("RGB")
else:
img = Image.open(self.args.img_path).convert("RGB")
img = img.resize((self.config.data.image_size, self.config.data.image_size), Image.ANTIALIAS)
img = np.array(img) / 255
img = torch.from_numpy(img).type(torch.FloatTensor).permute(2, 0, 1).unsqueeze(dim=0)
img = img.to(self.config.device)
tvu.save_image(img, os.path.join(self.args.image_folder, f'0_orig.png'))
x0 = (img - 0.5) * 2.
# ----------- Model -----------#
if self.config.data.dataset == "LSUN":
if self.config.data.category == "bedroom":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/bedroom.ckpt"
elif self.config.data.category == "church_outdoor":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/church_outdoor.ckpt"
elif self.config.data.dataset == "CelebA_HQ":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/celeba_hq.ckpt"
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
pass
else:
raise ValueError
if self.config.data.dataset in ["CelebA_HQ", "LSUN"]:
model = DDPM(self.config)
if self.args.model_path:
ckpt = torch.load(self.args.model_path)
else:
ckpt = torch.hub.load_state_dict_from_url(url, map_location=self.device)
learn_sigma = False
print("Original diffusion Model loaded.")
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
model = i_DDPM(self.config.data.dataset)
if self.args.model_path:
ckpt = torch.load(self.args.model_path)
else:
ckpt = torch.load(MODEL_PATHS[self.config.data.dataset])
learn_sigma = True
print("Improved diffusion Model loaded.")
else:
print('Not implemented dataset')
raise ValueError
model.load_state_dict(ckpt)
model.to(self.device)
model = torch.nn.DataParallel(model)
model.eval()
# ----------- Loss -----------#
print("Loading losses")
id_loss_func = id_loss.IDLoss().to(self.device).eval()
clip_loss_func = CLIPLoss(
self.device,
lambda_direction=0,
lambda_patch=0,
lambda_global=1,
lambda_manifold=0,
lambda_texture=0,
clip_model=self.args.clip_model_name)
# ----------- Invert Image to Latent -----------#
seq_inv = np.linspace(0, 1, self.args.n_inv_step) * self.args.t_0
seq_inv = [int(s) for s in list(seq_inv)]
seq_inv_next = [-1] + list(seq_inv[:-1])
print(f"Finding latent")
with torch.no_grad():
x = x0.clone()
with tqdm(total=len(seq_inv), desc=f"Inversion process") as progress_bar:
for it, (i, j) in enumerate(zip((seq_inv_next[1:]), (seq_inv[1:]))):
t = (torch.ones(n) * i).to(self.device)
t_prev = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_prev, models=model,
logvars=self.logvar,
sampling_type='ddim',
b=self.betas,
eta=0,
learn_sigma=learn_sigma)
progress_bar.update(1)
x_lat0 = x.clone()
tvu.save_image((x_lat0 + 1) * 0.5, os.path.join(self.args.image_folder,
f'1_lat_ninv{self.args.n_inv_step}.png'))
# ----------- Latent Optimization -----------#
print(f"CLIP loss latent optimization")
print(f"Sampling type: {self.args.sample_type.upper()} with eta {self.args.eta}")
if self.args.n_train_step != 0:
seq_train = np.linspace(0, 1, self.args.n_train_step) * self.args.t_0
seq_train = [int(s) for s in list(seq_train)]
print('Uniform skip type')
else:
seq_train = list(range(self.args.t_0))
print('No skip')
seq_train_next = [-1] + list(seq_train[:-1])
for txt_idx, (src_txt, trg_txt) in enumerate(zip(self.src_txts, self.trg_txts)):
x_lat = nn.Parameter(x_lat0.clone())
optimizer = torch.optim.Adam([x_lat], weight_decay=0, lr=self.args.lr_clip_lat_opt)
clip_loss_func.target_direction = None
with torch.set_grad_enabled(True):
for it in range(self.args.n_iter):
x = x_lat
optimizer.zero_grad()
with tqdm(total=len(seq_train), desc=f"Generative process {trg_txt}-{it}") as progress_bar:
for i, j in zip(reversed(seq_train), reversed(seq_train_next)):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
eta=self.args.eta,
learn_sigma=learn_sigma)
progress_bar.update(1)
loss_clip = (2 - clip_loss_func(x0, src_txt, x, trg_txt)) / 2
loss_clip = -torch.log(loss_clip)
loss_id = torch.mean(id_loss_func(x0, x))
loss_l1 = nn.L1Loss()(x0, x)
loss = self.args.clip_loss_w * loss_clip + self.args.id_loss_w * loss_id + self.args.l1_loss_w * loss_l1
loss.backward()
print(f"CLIP opt: loss_clip: {loss_clip:.3f}, loss_id: {loss_id:.3f}, loss_l1: {loss_l1:.3f}")
tvu.save_image((x + 1) * 0.5, os.path.join(self.args.image_folder,
f'2_clip_{trg_txt.replace(" ", "_")}_t{self.args.t_0}_{it}_ngen{self.args.n_train_step}.png'))
optimizer.step()
def edit_images_from_dataset(self):
# ----------- Models -----------#
print(self.args.exp)
if self.config.data.dataset == "LSUN":
if self.config.data.category == "bedroom":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/bedroom.ckpt"
elif self.config.data.category == "church_outdoor":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/church_outdoor.ckpt"
elif self.config.data.dataset == "CelebA_HQ":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/celeba_hq.ckpt"
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
pass
else:
raise ValueError
models = []
model_paths = [None, self.args.model_path]
for model_path in model_paths:
if self.config.data.dataset in ["CelebA_HQ", "LSUN"]:
model_i = DDPM(self.config)
if model_path:
ckpt = torch.load(model_path)
else:
ckpt = torch.hub.load_state_dict_from_url(url, map_location=self.device)
learn_sigma = False
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
model_i = i_DDPM(self.config.data.dataset)
if model_path:
ckpt = torch.load(model_path)
else:
ckpt = torch.load(MODEL_PATHS[self.config.data.dataset])
learn_sigma = True
else:
print('Not implemented dataset')
raise ValueError
model_i.load_state_dict(ckpt)
model_i.to(self.device)
model_i = torch.nn.DataParallel(model_i)
model_i.eval()
print(f"{model_path} is loaded.")
models.append(model_i)
# ----------- Precompute Latents thorugh Inversion Process -----------#
print("Prepare identity latent")
seq_inv = np.linspace(0, 1, self.args.n_inv_step) * self.args.t_0
seq_inv = [int(s) for s in list(seq_inv)]
seq_inv_next = [-1] + list(seq_inv[:-1])
n = 1
img_lat_pairs_dic = {}
for mode in ['test']:
img_lat_pairs = []
pairs_path = os.path.join('precomputed/',
f'{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
if os.path.exists(pairs_path):
print(f'{mode} pairs exists')
img_lat_pairs_dic[mode] = torch.load(pairs_path)
for step, (x0, x_id, e_id) in enumerate(img_lat_pairs_dic[mode]):
tvu.save_image((x0 + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_0_orig.png'))
tvu.save_image((x_id + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_1_rec.png'))
if step == self.args.n_precomp_img - 1:
break
continue
else:
train_dataset, test_dataset = get_dataset(self.config.data.dataset, DATASET_PATHS, self.config)
loader_dic = get_dataloader(train_dataset, test_dataset, bs_train=self.args.bs_train,
num_workers=self.config.data.num_workers)
loader = loader_dic[mode]
for step, img in enumerate(loader):
x0 = img.to(self.config.device)
tvu.save_image((x0 + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_0_orig.png'))
x = x0.clone()
with torch.no_grad():
with tqdm(total=len(seq_inv), desc=f"Inversion process {mode} {step}") as progress_bar:
for it, (i, j) in enumerate(zip((seq_inv_next[1:]), (seq_inv[1:]))):
t = (torch.ones(n) * i).to(self.device)
t_prev = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_prev, models=models,
logvars=self.logvar,
sampling_type='ddim',
b=self.betas,
eta=0,
learn_sigma=learn_sigma,
ratio=0)
progress_bar.update(1)
x_lat = x.clone()
tvu.save_image((x_lat + 1) * 0.5, os.path.join(self.args.image_folder,
f'{mode}_{step}_1_lat_ninv{self.args.n_inv_step}.png'))
with tqdm(total=len(seq_inv), desc=f"Generative process {mode} {step}") as progress_bar:
for it, (i, j) in enumerate(zip(reversed((seq_inv)), reversed((seq_inv_next)))):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=models,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
eta=self.args.eta,
learn_sigma=learn_sigma,
ratio=0)
progress_bar.update(1)
img_lat_pairs.append([x0, x.detach().clone(), x_lat.detach().clone()])
tvu.save_image((x + 1) * 0.5, os.path.join(self.args.image_folder, f'{mode}_{step}_1_rec.png'))
if step == self.args.n_precomp_img - 1:
break
img_lat_pairs_dic[mode] = img_lat_pairs
pairs_path = os.path.join('precomputed/',
f'{self.config.data.category}_{mode}_t{self.args.t_0}_nim{self.args.n_precomp_img}_ninv{self.args.n_inv_step}_pairs.pth')
torch.save(img_lat_pairs, pairs_path)
# ----------- Generative Process -----------#
print(f"Sampling type: {self.args.sample_type.upper()} with eta {self.args.eta}")
if self.args.n_test_step != 0:
seq_test = np.linspace(0, 1, self.args.n_test_step) * self.args.t_0
seq_test = [int(s) for s in list(seq_test)]
print('Uniform skip type')
else:
seq_test = list(range(self.args.t_0))
print('No skip')
seq_test_next = [-1] + list(seq_test[:-1])
print("Start evaluation")
eval_modes = ['test']
for mode in eval_modes:
img_lat_pairs = img_lat_pairs_dic[mode]
for step, (x0, x_id, x_lat) in enumerate(img_lat_pairs):
with torch.no_grad():
x = x_lat
with tqdm(total=len(seq_test), desc=f"Eval iteration") as progress_bar:
for i, j in zip(reversed(seq_test), reversed(seq_test_next)):
t = (torch.ones(n) * i).to(self.device)
t_next = (torch.ones(n) * j).to(self.device)
x = denoising_step(x, t=t, t_next=t_next, models=models,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
eta=self.args.eta,
learn_sigma=learn_sigma,
ratio=self.args.model_ratio,
hybrid=self.args.hybrid_noise,
hybrid_config=HYBRID_CONFIG)
progress_bar.update(1)
print(f"Eval {step}")
tvu.save_image((x + 1) * 0.5,
os.path.join(self.args.image_folder,
f'{mode}_{step}_2_clip_ngen{self.args.n_test_step}_mrat{self.args.model_ratio}.png'))
def edit_one_image(self):
# ----------- Data -----------#
n = self.args.bs_test
if self.args.align_face and self.config.data.dataset in ["FFHQ", "CelebA_HQ"]:
try:
img = run_alignment(self.args.img_path, output_size=self.config.data.image_size)
except:
img = Image.open(self.args.img_path).convert("RGB")
else:
img = Image.open(self.args.img_path).convert("RGB")
img = img.resize((self.config.data.image_size, self.config.data.image_size), Image.ANTIALIAS)
img = np.array(img)/255
img = torch.from_numpy(img).type(torch.FloatTensor).permute(2, 0, 1).unsqueeze(dim=0).repeat(n, 1, 1, 1)
img = img.to(self.config.device)
tvu.save_image(img, os.path.join(self.args.image_folder, f'0_orig.png'))
x0 = (img - 0.5) * 2.
# ----------- Models -----------#
if self.config.data.dataset == "LSUN":
if self.config.data.category == "bedroom":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/bedroom.ckpt"
elif self.config.data.category == "church_outdoor":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/church_outdoor.ckpt"
elif self.config.data.dataset == "CelebA_HQ":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/celeba_hq.ckpt"
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
pass
else:
raise ValueError
models = []
if self.args.hybrid_noise:
model_paths = [None] + HYBRID_MODEL_PATHS
else:
model_paths = [self.args.model_path]
# for model_path in model_paths:
# print('attempting load', model_path)